Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we erase the items in range-based for loop in c++11 [duplicate]

Tags:

c++

c++11

I would like to erase all the items less than v in C++11 standard container set, here is my code:

void delete_less_than(set<int> & ss, int const v) {
   for (auto item: ss) {
      if (item < v) {
        ss.erase(ss.find(item));
      } else break;
  }  
}

Will the code work properly? I seems okay on my computer (g++ 4.7.3), but loops infinitely on some online judge where I submit my code.

like image 326
notbad Avatar asked Dec 01 '13 20:12

notbad


1 Answers

That's not what the range-based loop is for. Don't use it; use a normal for loop instead. The range-based version is only if you want to do something with every element in the container, without mutating the container.

for (auto it = ss.begin(); it != ss.end(); )
{
    if (*it < v) { ss.erase(it++); }
    else         { ++it;           }
}

Even simpler:

ss.erase(ss.begin(), ss.lower_bound(v));
like image 117
Kerrek SB Avatar answered Sep 28 '22 09:09

Kerrek SB