In this article we will discuss how to discuss different ways to reverse a complete std::list or a sub list inside a list.

Suppose we have a list of strings i.e.

Now we want to reverse it i.e.

Let’s see how to do that in 2 different ways,

Reverse a List in place using std::list::reverse()

std::list has a member function reverse() i.e.

It reverses the order of the elements in the list.

Let’s use this to reverse the contents of list of strings i.e.

Reverse a List using STL Algorithm std::reverse()

STL Algorithms provides a generic function to reverse a given range i.e.

It Reverse the order of elements in given range.

Let’s use to it reverse the complete list i.e.

It has one advantage over the previous list::reverse(), we can use it it reverse a specific range in the list, not the complete list.

Reverse a Sub List inside a std::list using std::reverse()

Let’s use std::reverse to reverse the first three elements in the list i.e.

Suppose if given list,

Let’s reverse the first 3 elements only i.e.

{ “the” , “of” , “is” , “Hi” , “Hello” , “from” };

Now let’s see how to that using std::reverse(),

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.