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

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);
}

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));

Tags:

C++

Vector