Reverses the order of the elements

You're viewing an older version of this page (#4151). View the current version.

View versions (1)

Definition

The reverse() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class BidirectionalIterator >
   void reverse(
      BidirectionalIterator first, 
      BidirectionalIterator last
   );

Parameters:

ParameterDescription
firstA bidirectional iterator pointing to the position of the first element in the range within which the elements are being permuted
lastA bidirectional iterator pointing to the position one past the final element in the range within which the elements are being permuted

Description

Reverse function reverses the order of the elements within a range.

Return Value

None.

Complexity

The complexity is linear; calls swap one half the length of range [first,last) times.

References

Example 1
Problem

This example of program illustrates the functionality of reverse() algorithm.

Workings
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
  vector <int> v1;
  vector <int>::iterator Iter1;

  int i;
  for ( i = 0 ; i <= 9 ; i++ )
    v1.push_back( i );

  cout <<"The original vector v1 is:\n ( " ;
  for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
    cout <<*Iter1<<" ";
  cout <<")."<<endl;

  // Reverse the elements in the vector 
  reverse (v1.begin( ), v1.end( ) );

  cout <<"The modified vector v1 with values reversed is:\n ( " ;
  for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
    cout <<*Iter1<<" ";
  cout <<")."<<endl;

  return 0;
}
Solution

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 ).

See Also