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]);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With