c++stlremove-if

counting deletions in remove_if (c++ STL)


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.


Solution

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