c++ – Removing an item from a container using the c ++ 11 for loop syntax


Is it possible using the range for loop syntax:

for(auto& i: mapR) {
    // ...

to traverse the container, remove the current element from the container if, for example, it falls under a certain condition? Or would you have to use the iterator version like below?

for(auto i = mapR.begin(); i != mapR.end(); ) {   
    // ... 
    i = mapR.erase(i); 


The standard defines a range-based for loop equivalent to the following code:

    auto && __range = range - init;
    for(auto __begin = begin - expr,
        __end = end - expr;
        __begin != __end;
        ++__begin) {
        for-range-declaration = *__begin;

As you can see, iterators are used internally, therefore, inside a loop, you cannot use code that would invalidate the iterators.

To answer your question, no – you cannot remove items from C ++ containers in which this operation results in invalid iterators.

Scroll to Top