Javatpoint Logo
Javatpoint Logo

C++ Algorithm replace_if()

C++ Algorithm replace_if() function is used to assign new_value to all the elements in the range [first, last) for which pred predicate returns true.

This function examines each element in a range and replaces it if it satisfies a specified predicate.

Syntax

Parameter

first: A forward iterator pointing to the initial position in the range from which elements are being replaced.

last: A forward iterator pointing to the final position in the range from which elements are being replaced.

pred: The unary predicate function that must be satisfied is the value of the element is to be replaced.

new_value: The new value assigned to the elements whose old value satisfies the predicate.

Return value

None

Complexity

Complexity is linear in the distance within first and last. Applies pred to each element and assigns to those matching also.

Data races

The objects in the range [first1, last1) are accessed and potentially modified.

Exception safety

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

Output:

10,10,2,10,2,

The above example determines odd numbers from vector v and replaces all found element with 10.

Example 2

Let's see another simple example:

Output:

The original vector v1 is:
 ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 ).
The vector v1 with a value 70 replacing those
 elements satisfying the greater6 predicate is:
 ( 4 70 70 70 0 5 70 1 6 70 3 70 70 2 ).

In the above example, vector v1 with a value 70 replacing those elements satisfying the greater 6 predicate.

Example 3

Let's see another simple example:

Output:

Here are the values in the vector:
1 2 2 3 4 5 2 6 
Now we replace all values divisible by 3 with 123.
Here are the revised contents of the vector:
1 2 2 123 4 5 2 123  

Example 4

Let's see another simple example:

Output:

myvector contains: 0 2 0 4 0 6 0 8 0

Next TopicC++ Algorithm





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA