我将以下数据结构存储在一个类中。
class MyClass {
private:
std::map<std::string, std::set<std::string>> myMap;
public:
void remove(std::string id); //trying to remove items from sets inside myMap
}
然后有一种方法可以尝试从集合中删除项目。我尝试了以下两种方法,但都没有奏效。方法一,使用for范围。
for (auto pair : myMap) {
auto set = pair.second;
if (set.count(id)) {
set.erase(id);
}
}
方法 2,使用iterator.
auto it = myMap.begin();
while (it != myMap.end()) {
auto set = it->second;
if (set.count(id)) {
set.erase(id);
}
it++;
}
从 C++ 中的地图内的集合中删除元素的正确方法是什么?请注意,当我myMap定义为std::map<std::string, std::set<std::string>*>(指针)时,我的代码曾经可以工作。