forward_list::reverse( ) in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the working of forward_list::reverse( ) function in C++ STL.

What is a Forward List?

Forward list can be understood as a singly linked list where the tracking can be done only in forward direction but not in a backward direction whereas in the list we can track the elements in both the direction i.e. the element holds the two links one is for forward element and another one is for backward element. Forward lists are therefore fast because they have to hold only one link which will be of a forward element. Forward elements can be inserted and deleted in a constant time.

What is a forward_list::reverse( ) function?

forward_list::reverse( ) is a function in C++ Standard Template Library(STL) that is used to reverse the order of the elements present in the forward list.


forwardlist_name.reverse( )


This function doesn’t have any parameter.

Return Value

This function doesn’t have any return value. It only performs operation of reversing the list


Input-: List of elements are: 57 99 54 34 84
Output–: Reversed elements of list are: 84 34 54 99 57
Input-: List of elements are: 40 30 60 90 70
Output–: Reversed elements of list are: 70 90 60 30 40

Approach that is used in the below program is as follows

  • First initialize the list.

  • Then we will print the forward list before applying reverse () function.

  • Then we defines the forward.reverse( ) function present in a header file in C++.

  • Then we will display the reversed forward list


// C++ code to demonstrate the working of forward_list::reverse( )
Using namespace std;
Int main( ){
   // initializing forward list
   forward_list<int> forward = {10,20,30,40,50};
   cout<< “ List of elements : ”;
   for(auto it = forward.start( ); it != forward.end( ); ++it)
      cout<< *it<< “ “;
   // defining of function that performs the reverse operation
   forward.reverse( );
   cout<< “ Reversed elements list”;
   for( auto it =forward.start( ); it != forward.end( ); ++it)
      cout<< *it<< “ “;
   return 0;


If we run the above code then it will generate the following output

Reversed elements list : 50 40 30 20 10
Published on 28-Feb-2020 11:18:22