Javatpoint Logo
Javatpoint Logo

C++ Algorithm replace_copy()

C++ Algorithm replace_copy() function is used to make a copy of the range [first, last) and replaces all old_value by the value new_value into it. It uses operator= to make the copy and to compare the elements it uses operator==.

This function examines each element in a source range and replaces it if it matches a specified value while copying the result into a new destination range.

Syntax

Parameter

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

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

result: An output iterator pointing to the first element of the range where the resulting sequence is stored.

old_value: The old value of the element being replaced.

new_value: The new value assigned to the elements with the old value.

Return value

replace_copy() function returns an output iterator pointing to the position that points to the last element written in the result sequence.

Complexity

Complexity is linear in the distance within first and last and performs a comparison and an assignment for each element.

Data races

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

The objects in the range within result and the returned value are modified.

Exception safety

This function throws an exception if any of the element comparison, 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_copy():

Output:

3,10,2,10,2,

Example 2

Let's see another simple example:

Output:

myvector contains: 10 99 30 15 99 10 10 99

Example 3

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 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ).
The vector v1 with a value 70 replacing that of 7 is:
 ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 1 4 70 70 70 0 5 70 1 6 9 3 70 8 2 1 ).
The list copy L1 of v1 with the value 0 replacing that of 7 is:
 ( 4 1 1 1 0 5 1 1 6 9 3 1 8 2 0 ).

Example 4

Let's see another simple example:

Output:

Before replace_copy : A B C D E F G 
After replace_copy : Z B C D E F G

In the above example, function replace_copy() is used to replace 'A' at v.begin() with Z and copy it to v.begin() position.


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