How to remove multiple elements from std :: vector <> by index using the delete function?

I have a vector afor storing values [0 1 2 3 5]and another vector removelistfor storing indexes that need to be removed [0 1 2]to be left [3 5]at the end. When I implement the following code, it will delete the elements unexpectedly, as the vector awill reorder during the process. Is there a way to achieve my goal?

 for (int i = 0; i<removelist.size() ; i++)     
    a.erase(a.begin() + removelist[i]);
+4
source share
3 answers

Cancel the order of deleting values, i.e. use reverse iterators removelist. This, of course, depends on the sorting removelist.

Maybe 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);
}
+1

, 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));
+2

- , , :

// pseudocode:
vector tmp;
tmp.reserve(a.size() - removelist.size());
for (i=0; i<a.size(); ++i) {
    if (i not in removelist) {
        tmp.push_back(a[i]);
    }
}
a.swap(tmp);

:

  • , , .
  • . a .
  • removelst , .
  • , . " " ?
0

Source: https://habr.com/ru/post/1626302/


All Articles