C++ Standard Library C++ STL Library

C++ <algorithm> - reverse() Function



The C++ algorithm::reverse function is used to reverse the order of the elements in the range [first,last).

Syntax

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

Parameters

first Specify initial position of the bidirectional iterator. The range used is [first,last).
last Specify final position of the bidirectional iterator. The range used is [first,last).

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::reverse function is used to reverse the order of the elements in the given vector.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std; 

int main (){
  vector<int> vec{10, 20, 30, 40, 50};
  vector<int>::iterator it;

  cout<<"Before reverse call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //reverse the order of the elements
  reverse(vec.begin(), vec.end());

  cout<<"\nAfter reverse call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before reverse call, vec contains: 10 20 30 40 50
After reverse call, vec contains: 50 40 30 20 10

❮ C++ <algorithm> Library