Home >Backend Development >C++ >What Happens When You Erase a Map Element During Iteration in C ?

What Happens When You Erase a Map Element During Iteration in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 16:02:11995browse

What Happens When You Erase a Map Element During Iteration in C  ?

What Happens if You Call erase() on a Map Element While Iterating from Begin to End?

When iterating through a map in C , it's important to consider the behavior of erasing elements while iterating. This operation may lead to unexpected results if not handled correctly.

C 11

In C 11, the erase() method has been improved and is now consistent across all container types. When an element is erased, the erase() method returns the next iterator. This allows you to continue iterating the map without encountering any problems.

The following code demonstrates the correct way to erase elements from a map while iterating in C 11:

auto pm_it = port_map.begin();
while (pm_it != port_map.end()) {
    if (pm_it->second == delete_this_id) {
        pm_it = port_map.erase(pm_it);
    } else {
        ++pm_it;
    }
}

C 03

In C 03, erasing elements from a map while iterating can lead to invalidated iterators. To avoid this issue, you should iterate through the map using a loop variable that is incremented outside of the erase() operation.

The following code demonstrates the correct way to erase elements from a map while iterating in C 03:

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while (pm_it != port_map.end()) {
    if (pm_it->second == delete_this_id) {
        port_map.erase(pm_it++); // Use iterator.
        // Note the post increment.
        // Increments the iterator but returns the
        // original value for use by erase
    } else {
        ++pm_it; // Can use pre-increment in this case
        // To make sure you have the efficient version
    }
}

The above is the detailed content of What Happens When You Erase a Map Element During Iteration in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn