How to implement deleting elements while iterating through a C++ map?
In C++, iterators can be used to iterate through and delete elements in a map. One common implementation is as follows:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "Apple";
myMap[2] = "Banana";
myMap[3] = "Orange";
myMap[4] = "Grape";
// 遍历并删除符合条件的元素
for(auto it = myMap.begin(); it != myMap.end(); ) {
if(it->second == "Banana") {
it = myMap.erase(it); // 删除元素并更新迭代器
}
else {
++it;
}
}
// 输出剩余元素
for(const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
This code segment creates a map and then iterates through it using an iterator. During the iteration, it checks if the value of each element is “Banana”. If it is, it deletes the element using the erase() function and updates the iterator to point to the next element. If it is not, it increments the iterator to the next element. This allows for iterating and deleting all elements in the map with a value of “Banana”.
After using the erase() function to delete an element, the iterator becomes invalid, so it must be updated to point to the next element to avoid undefined behavior.