1

Is there any way to count the number of deletions made by the remove_if function in the STL?

Specifically I am passing forward and back iterators each to vectors of ints, and have a lambda as the third argument as a comparative value for remove_if to determine if the vector should be deleted based on values in the vector. I want to know if there is a way to know the number of vectors deleted by remove_if afterwards.

Also, as a side question: I declare these vectors dynamically, so I am not sure if calling remove_if on these is bad practice.

user313
  • 681
  • 1
  • 8
  • 21

2 Answers2

5

Count the of elements before remove_if, and after.

auto old_size = list.size();
auto new_end = std::remove_if(list.begin(), list.end(), ...);
auto new_size = std::distance(list.begin(), new_end);
auto deletions = old_size - new_size;
adam
  • 240
  • 1
  • 7
  • Using `std::distance` is correct, however "count the elements before and after remove_if" is imprecise, as `remove_if` doesn't change the number of elements. – Antonio Jun 17 '22 at 01:08
1

Longer answer (though @kukac 's) is correct.

remove and (remove_if) do not actually remove elements from the vector; they merely shuffle them to the end, and return an iterator to the start of the "removed" elements. To actually get rid of them, you call erase. This is called the "erase-remove idiom", and there's lots of posts about that.

Like this (uncompiled code):

vector<int> v = {1,2,3,4,5}; // v.size() == 5
auto it = remove_if(v.begin(), v.end(), is_odd);
// now v looks something like this: {2,4,5,1,3}
//   the v.size() is still == 5
//   and it "points to" '5'
v.erase(it, v.end()); // erase all the elements that were "removed"
// now v looks something like this: {2,4}
//   the v.size() is now == 2
Antonio
  • 19,451
  • 13
  • 99
  • 197
Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
  • 1
    @Antonio, you are incorrect. `v.erase(v.end(), v.end())` is perfectly fine; it removes all the elements in the half open range `[v.end(), v.end())` - of which there are none. – Marshall Clow Jun 18 '22 at 02:55
  • You are right, I have deleted my wrong comment and cancelled my vote. – Antonio Jun 21 '22 at 07:04