Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing an element from a container while inside a range-based for loop

I want to erase an element from a container which is being currently used within a ranged-based for loop. Will this cause undefined behaviour? Or will the next value of element after erase() be what the next element is supposed to be if I didn't call erase()?

Example:

std::map<int, int> someMap;
/* Fill in someMap */
for (auto& element : someMap)
{
    /* ... */
    if ( /* Some condition */ )
        someMap.erase(element.first);
}
like image 980
小太郎 Avatar asked Dec 24 '11 13:12

小太郎


1 Answers

It should be a undefined behavior. Because according to 14882/2011 the range-based for statement is equivalent to:

auto && __range = range-init;
for ( auto __begin = begin-expr(__range),
   __end = end-expr(__range);
   __begin != __end;
   ++__begin ) {
   for-range-declaration = *__begin;
   statement
}
like image 98
Shawnone Avatar answered Oct 12 '22 23:10

Shawnone