乐闻世界logo
搜索文章和话题

What happens if you call erase() on a map element while iterating from begin to end?

1个答案

1

In C++, if you call the erase() function on map elements during iteration, you must exercise caution because it may cause the iterator to become invalid, leading to undefined behavior.

Specifically, when you delete an element from std::map, the iterator pointing to that element becomes invalid immediately. This means that if you use erase() incorrectly in a loop and continue using the old iterator after deletion, it may cause the program to crash or other errors.

The correct approach is to update the iterator when calling erase(). The erase() function returns an iterator pointing to the element immediately following the deleted one, which can be used to safely continue iteration. Here is an example:

cpp
#include <iostream> #include <map> int main() { std::map<int, std::string> myMap; // Initialize map myMap[1] = "one"; myMap[2] = "two"; myMap[3] = "three"; // Safely delete elements for (auto it = myMap.begin(); it != myMap.end(); ) { if (it->first == 2) { it = myMap.erase(it); // erase() updates the iterator } else { ++it; // Normal iteration } } // Output remaining elements for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

In this example, we safely remove the element with key 2 from std::map. Note that we do not reuse the old iterator after the erase() call; instead, we directly use the iterator returned by erase() to continue the loop. This ensures that the iterator remains valid and points to the correct element, avoiding potential errors or crashes.

2024年7月17日 10:28 回复

你的答案