C++ Algorithm reverse_copy()

C++ Algorithm reverse_copy() function is used to copy the elements from the range[first, last) to another range beginning at result in such a way that the elements in the range are in reverse order.

Syntax

Note: BidirectionalIterator is an iterator which is used to access any elements of a container in both forward and backward direction.

Parameter

first: A bidirectional iterator pointing the position of the first element in the range in which the elements are being reversed.

last: A forward iterator pointing the position one past the final element in the range in which the elements are being reversed.

result: Output iterator pointing to the initial position of the range to which elements are being copied.

Return value

This function returns an output iterator pointing to the end of the copied range [first, last) to where the altered sequence of elements is being copied.

Complexity

Complexity is linear in the range [first, last): performs an assignment to each element.

Data races

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

The object in the range between result and returned value are modified.

Exceptions

This function throws an exception if either an element assignment or an operation on iterator throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

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

Output:

Before: 1 2 3 
After:  3 2 1

Example 2

Let's see another simple example to reverse the string:

Output:

Before Reverse: Hello Myself Nikita
After Reverse: atikiN flesyM olleH

Example 3

Let's see another simple example to reverse the range of numbers:

Output:

The original vector v1 is:
 ( 0 1 2 3 4 5 6 7 8 9 ).
The copy v2 of the reversed vector v1 is:
 ( 9 8 7 6 5 4 3 2 1 0 ).
The original vector v1 remains unmodified as:
 ( 0 1 2 3 4 5 6 7 8 9 ).

Example 4

Let's see another simple example:

Output:

Original order : 1. George  2.  John  3. Nikki  4. Alice  5.   Bob  6. Watson  

Reversing the order ... 
Reversed order : 1. Watson  2.   Bob  3. Alice  4. Nikki  5.  John  6. George  

Next TopicC++ Algorithm




Latest Courses