c++ - How to use erase-remove idiom and increment an iterator in a loop? -


i want loop through vector , remove item each time. believe should use erase-remove idiom. believe erase on vector invalidates of iterators. if that's case, how can use idiom in while loop?

here's broken example:

std::vector<int> vec = { 3, 6, 7, 5 };  auto itr = vec.begin(); while (itr != vec.end()) {     // i'll remove different element each iteration of loop.     // hard-coded "7" here simplicity:     auto position = std::remove(vec.begin(), vec.end(), 7);      vec.erase(position);     ++itr; } 

the purpose of code loop through vector , remove element each time. use while loop , iterator because size of vector changes after each iteration. i'll remove largest element each iteration, i'm not showing code keep simpler. so, elements removed in order: 7, 6, 5, 3. again, code isn't shown.

std::remove() moves elements (not 1 element!) of specified value end of container, , returns new logical past-end iterator. std::remove() not invalidate iterators, items not physically removed , container size not changed. values inside container moved around.

after have "removed" want remove, call erase() 1 time @ end physically remove items container.

try this:

std::vector<int> vec = { 3, 6, 7, 5 };  auto itr = vec.begin(); auto end = vec.end();  while (itr != end) {     end = std::remove(vec.begin(), end, ...);     ++itr; }  vec.erase(end, vec.end()); 

Comments