C++ Algorithm reverse()
C++ Algorithm reverse() function is used to reverse the order of the elements within a range [first, last).
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.
Return value
None
Complexity
Complexity is linear in the range [first, last): swaps elements.
Data races
The object in the range [first, last) are modified.
Exceptions
This function throws an exception if either an element is swapped 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 reverse the given string:
Output:
Before Reverse : Hello Myself Nikita After Reverse : atikiN flesyM olleH
Example 2
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 modified vector v1 with values reversed is: ( 9 8 7 6 5 4 3 2 1 0 ).
Example 3
Let’s see another simple example:
Output:
Before: 10 11 12 13 14 15 16 17 Reverse only from index 5 to 7 in array: 10 11 12 13 14 17 16 15 Reverse full array: 7654
Example 4
Let’s see another simple example:
Output:
Original order : 1. George 2. John 3. Nik 4. Alice 5. Bob 6. Watson Reversing the order .... Reversed order : 1. Watson 2. Bob 3. Alice 4. Nik 5. John 6. George