Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to erase multiple elements from std::vector<> by index using erase function?

Tags:

c++

vector

I have a vector a storing values [0 1 2 3 5] and other vector removelist storing the indexes to be removed [0 1 2] in order to leave [3 5] at the end. When I'm implementing the following code, it would remove items unexpectedly since the vector a will be changing order during the process. Is there any way for me to achieve my target?

 for (int i = 0; i<removelist.size() ; i++)     
    a.erase(a.begin() + removelist[i]);
like image 229
Tleung Avatar asked Jan 28 '16 07:01

Tleung


2 Answers

Reverse the order you remove values, i.e. use the reverse iterators of removelist. This of course relies on removelist being sorted.

Perhaps something like

std::sort(removelist.begin(), removelist.end());  // Make sure the container is sorted
for (auto &i = removelist.rbegin(); i != removelist.rend(); ++ i)
{
    a.erase(a.begin() + *i);
}
like image 160
Some programmer dude Avatar answered Sep 29 '22 07:09

Some programmer dude


Not necessarily more efficient, but you can do this without sorting using remove_if:

auto& rm = removelist; // for brevity

a.erase(remove_if(begin(a), end(a), [&](int i) {
  auto idx = distance(begin(v), find(begin(v), end(v), i));
  return find(begin(rm), end(rm), idx) != end(rm);
}, end(a));
like image 21
Yam Marcovic Avatar answered Sep 29 '22 05:09

Yam Marcovic