How to remove an item from a vector element by remove_if

(314 Views)


The task of removing elements with a certain property from a std::vector or other container leads to a functional style implementation. It uses loops and data iterations. You can do this in the following way:

std::vector<int> ints; ... ints.erase( std::remove_if(ints.begin(), ints.end(), [](int x){return x < 0;}), ints.end());
std::remove_if is defined in "algorithm" library. It removes value within a range. Transforms the range [first,last] into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range. Following are some properties of the function:
  • The function cannot alter the properties of the object like size of an array or a container containing the range of elements.
  • The relative order of the elements not removed is preserved.
  • The function uses operator "==" to compare the individual elements to val.

How to remove an item from a vector element by remove_if

Solution Worked 4 UpvotesUpvote

        

Solution Didn't Worked 2 DownvotesDownvote



Comments



Search