I have the following data structure stored in a class.
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
}
There is then a method to attempt to delete items from the sets. I tried the following 2 ways but neither worked. Approach 1, use for
range.
for (auto pair : myMap) {
auto set = pair.second;
if (set.count(id)) {
set.erase(id);
}
}
Approach 2, use iterator
.
auto it = myMap.begin();
while (it != myMap.end()) {
auto set = it->second;
if (set.count(id)) {
set.erase(id);
}
it++;
}
What's the right way of removing elements from the sets inside a map in C++? Note that my code used to work when I had myMap
defined as std::map<std::string, std::set<std::string>*>
(pointers).