0

Given a std::vector, I want to delete all elements which match a condition. I cannot see any simple way to do this, as I cannot specify a single value for the elements to be deleted.

Here is a simple example illustrating the problem. I want to delete elements from v that have their member k equal to a given value.

int kDelete = 123; // elements to be deleted
struct S
{
  int k;
  int data;
};
vector<S> v;
for(auto& s:v)
{
  if(s.k == k)
    v.erase(???); // what is the correct arg for erase?
}

Prior answers are contradictory with respect to whether erase invalidates implicit iterator, and whether the range limits are recalculated at each iteration. Also, they are several years old.

Woody20
  • 791
  • 11
  • 30
  • 4
    Don't `erase` `vector` elements inside a range based `for`-loop. You can use [`std::erase(v, kDelete);`](https://en.cppreference.com/w/cpp/container/vector/erase2) (C++20) instead of the whole loop – Ted Lyngmo Mar 13 '23 at 20:28
  • *I cannot see any simple way to do this* -- `v.erase(std::remove_if(v.begin(), v.end(), [&](auto& s) { return s.k == k;}), v.end());`. There must be a duplicate for this. – PaulMcKenzie Mar 13 '23 at 20:28
  • 1
    *Given a std::vector, I want to delete all elements which match a condition* -- [std::remove_if](https://en.cppreference.com/w/cpp/algorithm/remove). Also, look at the **Notes** section, especially the first sentence. – PaulMcKenzie Mar 13 '23 at 20:34
  • I have replaced the proposed method of using `erase` with copying only the elements to be kept to a new vector. This should be O(n), and is simple to understand. – Woody20 Mar 14 '23 at 17:35
  • Copying doesn't seem like a good solution. Move them - or, just use the erase–remove idiom suggested by @PaulMcKenzie - or the C++20 special `std::erase` version that I suggested. It doesn't get simpler than `std::erase(v, kDelete);` does it? – Ted Lyngmo Mar 14 '23 at 21:52

0 Answers0