C++ Algorithm remove_if()C++ Algorithm remove_if() function is used to eliminate all the elements that satisfy a predicate from a given range [first, last) without disturbing the order of the remaining elements.
SyntaxParameterfirst: A forward iterator pointing the position of the first element in the range from which elements are being removed. last: A forward iterator pointing the position one past the final element in the range from which elements are being removed. pred: The unary predicate function which accepts an element as an argument that must be satisfied is the value of an element is to be replaced. Return valueA forward iterator pointing the new end position (last) of the modified range or first element if first and last is equal. ComplexityComplexity is linear in the range [first, last): Applies pred to each element, and possibly performs assignments on some of them. Data racesThe object in the range [first, last) are accessed and potentially modified. Exception safetyThis function throws an exception if any of pred, the element assignments or the operation on an iterator throws an exception. Note: The invalid parameters cause an undefined behavior.Example 1Let's see the simple example to demonstrate the use of remove_if(): Output: Original vector : 1 2 3 4 5 6 7 8 9 10 After remove_if : 2 4 6 8 10 Example 2Let's see another simple example: Output: Vector v1 is ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 ). Vector v1 with elements satisfying greater6 removed is ( 4 0 5 1 6 3 2 1 6 9 3 7 8 2 ). Vector v1 resized elements satisfying greater6 removed is ( 4 0 5 1 6 3 2 ). Example 3Let's see another simple example: Output: Vector : China India Korea America Australia Pakistan Vector : China India Korea Pakistan Example 4Let's see another simple example to remove all spaces from a string by shifting all non-space characters to the left and then erasing the extra space. Output: Textwithsomespaces Textwithsomewhitespaces Next TopicC++ Algorithm |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India