C++ Algorithm remove()

C++ Algorithm remove() function is used to eliminate all the elements that are equal to val from a given range [first, last) without disturbing the order of the remaining elements.

  • This function cannot alter the size of the container.
  • It returns an iterator to the new end of the range.
  • Remove is stable, means that the relative order of the elements that are not equal to val is remain unchanged.
  • This function uses operator== to compare the individual elements to val.

Syntax

Parameter

first: 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.

val: A value that is to be removed from the range.

Return value

A forward iterator pointing the new end position (last) of the modified range or first element if first and last is equal.

Complexity

Complexity is linear in the range [first, last) and possibly performs an assignments on some of them.

Data races

The object in the range [first, last) are accessed and potentially modified.

Exception safety

This function throws an exception if any of the element comparisons, element assignments or the operation on an iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of remove():

Output:

range contains: 10 30 50 40 100

Example 2

Let's see another simple example to illustrate the difference between erase() and remove():

Output:

  Initial data set:	10 5 -8 5 1 4 

 Data set after remove: 10 -8 1 4 1 4 

 Data set after erase:  10 -8 1 4  

Example 3

Let's see another simple example:

Output:

Original vector :  10 20 30 30 20 10 10 20
After remove :  10 30 30 10 10

Example 4

Let'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 value 7 removed is ( 4 0 5 1 6 9 3 8 2 9 3 7 8 2 ).
Vector v1 resized with value 7 removed is ( 4 0 5 1 6 9 3 8 2 ).

Next TopicC++ Algorithm




Latest Courses