Javatpoint Logo
Javatpoint Logo

C++ Algorithm remove_copy_if()

C++ Algorithm remove_copy_if() function is used to copy all elements in the range [first, last) to the range beginning at result, except those elements for which pred returns true 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 removed is remain unchanged.

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.

result: An output iterator pointing to the initial position of the range to which elements are being removed.

pred: That must be satisfied is the value of an element is to be replaced.

Return value

A forward iterator pointing the new end position (last) of the copied range, which includes all elements in [first, last) except those for which pred will return true.

Complexity

Complexity is linear in the range [first, last): Applies pred to each element, and performs assignment operation for those which are not removed.

Data races

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

The objects in the range between result and the returned value are changed.

Exceptions

This function throws an exception if any of pred, the element assignments or the operations on 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_copy_if():

Output:

2,4,6,8,

Example 2

Let's see another simple example:

Output:

elements of v1 before remove_copy: 10 11 12 13 14 15 16 17 18 19 20 
elements of v1 after remove_copy: 10 11 12 13 14 15 16 17 18 19 20 
After removing Odd Numbers from v1 copy result in vector v2
10 12 14 16 18 20 0 0 0 0

Example 3

Let's see another simple example:

Output:

Numbers { 10 20 10 15 12 25 30 10  }

Total number of elements copied to Result = 6
Result { 10 20 10 15 12 10 0 0  }

Example 4

Let's see another simple example:

Output:

The original vec1 vector data: 0 1 2 3 4 5 6 7 8 9 10 5 5 5 

The original vec1 vector data randomly shuffled: 4 10 5 5 0 5 5 1 6 9 3 7 8 2 

After the remove_copy_if() operation, the vec1 vector is left unchanged as: 4 10 5 5 0 5 5 1 6 9 3 7 8 2 

vec2 vector is a copy of vec1 vector with values greater than 7 removed: 4 5 5 0 5 5 1 6 3 7 2

Next TopicC++ Algorithm




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA