如何在c++中比较映射中的键和值

How to compare KEYs to VALUEs in maps in C++?

本文关键字:映射 键和值 比较 c++      更新时间:2023-10-16

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

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

还提供了这个remove函数void removeResource(T* a),该函数的目标是在map中搜索参数(a),如果找到该参数,则从map中删除与该参数相关的值和键。

我所做的是:

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 studio编译器指向if (resources.at(it) == a).

请告诉我哪里做错了。

for (auto it = resources.begin(); it != resources.end();) {
     if (it->second == a) {
         it = resources.erase(it);
     }
     else {
         ++it;
     }
}