【问题标题】:How to compare KEYs to VALUEs in maps in C++?如何在 C++ 的地图中比较 KEY 和 VALUE?
【发布时间】:2015-09-26 22:40:49
【问题描述】:

我得到了一个 HashMap 的声明,它是这样的:

HashMap<String, T*> resources; //given by my professor

还提供了这个删除函数 void removeResource(T* a),这个函数的目标是在映射中搜索参数 (a),如果找到该参数,它会删除该值以及地图中与之关联的键。

所以我所做的是:

void removeResource(T* a) //function part given by my professor
        {
            //find the resource and remove it from the map

            for (auto it = resources.begin(); it != resources.end(); it++){
                if (resources.at(it) == a)
                    resources.erase(it);
            }
        }

Visual Studios 编译器抱怨指向 if (resources.at(it) == a)

请帮我看看我哪里做错了。

【问题讨论】:

  • 提示:你已经有了迭代器,it。您可以从it直接获得哪些信息?
  • 我们不知道HashMap 是什么,也不知道错误/投诉是什么,因为您也没有提供。帮助我们帮助您和编辑您的帖子,并提供该信息和任何其他相关信息。
  • 你读过anydocs吗?这是相当清楚的。此外,擦除会使任何迭代器和对已擦除元素的引用无效(您不能通过迭代器 erase 元素而只增加最后一个)。
  • 回答 Captain Obvlious,这是我从 VS 得到的错误消息:Error 22 error C2679: binary '[' : no operator found which take a right-hand operand of type 'std: :_Tree_iterator<:_tree_val _kty>>>>' (或没有可接受的转换) c:\users\franm\od\documents\gam531\lab01\ scs_emperor\emperor_engine\emperor_engine\resourcemanager.hpp 125 1 Emperor_Engine

标签: c++ hashmap maps


【解决方案1】:
for (auto it = resources.begin(); it != resources.end();) {
     if (it->second == a) {
         it = resources.erase(it);
     }
     else {
         ++it;
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多