The task of removing elements with a certain property from a std::vector
or other container lends itself to a functional style implementation: Why bother with loops, memory deallocation and moving data around correctly?
However the standard way of doing this in C++ seems to be the following idiom:
std::vector<int> ints;
...
ints.erase(
std::remove_if(ints.begin(),
ints.end(),
[](int x){return x < 0;}),
ints.end());
This example removes all elements less than zero from an integer vector.
I find it not only ugly but also easy to use incorrectly. It is clear that std::remove_if
cannot change the size of the vector (as its name would suggest) because it only gets iterators passed. But many developers, including myself, don't get that in the beginning.
So is there a safer and hopefully more elegant way to achieve this? If not, why?
remove_erase_if(ints, [](int x){return x < 0;});
(since 2010.) – Trejo