Single statement method to remove elements from container
-
11-07-2019 - |
Question
Is there a single algorithm that removes elements from a container as happens in the following code?
vec_it = std::remove_if( vec.begin(), vec.end(), pred );
vec.erase( vec_it, vec.end() );
Solution
The idiomatic way to do it is like jalf has said. You can build your own function to do that more easily:
template<typename T, typename Pred> void erase_if(T &vec, Pred pred)
{
vec.erase(std::remove_if(vec.begin(), vec.end(), pred), vec.end());
}
So you can use
std::vector<int> myVec;
// (...) fill the vector. (...)
erase_if(myVec, myPred);
OTHER TIPS
You mean like this?
vec.erase( std::remove_if( vec.begin(), vec.end(), pred ), vec.end() );
That's the idiomatic way to do it.
I don't know. Maybe there is. But if there is, then it will be a hell of a statement. Nobody will be able to understand or maintain it. If those two lines do what you want, just stick with them. They are perfectly good.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow