reverse() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). reverse() is a function in the STL that reverses a given container in the specified range.

Syntax:

reverse(iterator_begin, iterator_end);

Parameters: The reverse() method accepts 2 parameters:

  • iterator_begin: Bidirectional iterator to initial position
  • iterator_end: Bidirectional iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )

Return value: none

Example of reverse() method

#include <iostream>
#include <algorithm>
#include <list>

using namespace std;

int main()
{
    list<int> mylist;

    mylist.push_back(4);
    mylist.push_back(2);
    mylist.push_back(1);
    mylist.push_back(6);

    cout<<"Before reverse: \n";
    for( list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
    {
        cout<<*it<<"  ";
    }
    cout<<endl;

    reverse(mylist.begin(),mylist.end());
    cout<<"After reverse: \n";
    for( list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
    {
        cout<<*it<<"  ";
    }

}

Output:

Before reverse:
4  2  1  6
After reverse:
6  1  2  4

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top