C++ Standard Library C++ STL Library

C++ <forward_list> - reverse() Function



The C++ forward_list::reverse function is used to reverse the order of elements of the forward_list container.

Syntax

void reverse() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the forward_list::reverse function is used reverse the order of elements of the forward_list called flist.

#include <iostream>
#include <forward_list>
using namespace std;
 
int main (){
  forward_list<int> flist{10, 20, 30, 40, 50};
  forward_list<int>::iterator it;

  cout<<"flist contains: ";
  for(it = flist.begin(); it != flist.end(); it++)
    cout<<*it<<" ";

  //Reverse the order of all elements of flist
  flist.reverse();
  
  cout<<"\nflist contains: ";
  for(it = flist.begin(); it != flist.end(); it++)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

flist contains: 10 20 30 40 50 
flist contains: 50 40 30 20 10 

❮ C++ <forward_list> Library