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.

std::list<std::string> listOfStrs = { "is", "of", "the", "Hi", "Hello", "from" };

Now we want to reverse it i.e.
from , Hello , Hi , the , of , is

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.

std::list::reverse()

It reverses the order of the elements in the list.

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

std::list<std::string> listOfStrs = { "is", "of", "the", "Hi", "Hello", "from" };

// Reverse the contents of List
listOfStrs.reverse();

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

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

void reverse (BidirectionalIterator first, BidirectionalIterator last);

It Reverse the order of elements in given range.

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

std::list<std::string> listOfStrs = { "is", "of", "the", "Hi", "Hello", "from" };

// Reverse the contents of List
std::reverse(listOfStrs.begin(), listOfStrs.end());

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,

{ "is", "of", "the", "Hi", "Hello", "from" };

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(),

std::list<std::string> listOfStrs = { "is", "of", "the", "Hi", "Hello", "from" };

//Reverse the list from first element to 3rd
std::reverse(listOfStrs.begin(),  std::next(listOfStrs.begin() , 3));

Complete example is as follows,
#include <list>
#include <algorithm>
#include <iterator>
#include <iostream>

/*
 * Print the contents of a list
 */
template <typename T>
void print(std::list<T> & listObj)
{
	std::copy(listObj.begin(), listObj.end(), std::ostream_iterator<T>(std::cout, " , "));
	std::cout<<std::endl;

}

int main()
{
	std::list<std::string> listOfStrs = { "is", "of", "the", "Hi", "Hello", "from" };

	print(listOfStrs);

	/* Reverse the list using list::reverse() member function */

	// Reverse the contents of List
	listOfStrs.reverse();

	print(listOfStrs);

	/* Reverse the list using std::reverse() global STL algorithm */

	// Reverse the contents of List
	std::reverse(listOfStrs.begin(), listOfStrs.end());

	print(listOfStrs);

	// Reverse the first 3 elements of list

	//Reverse the list from first element to 3rd
	std::reverse(listOfStrs.begin(),  std::next(listOfStrs.begin() , 3));

	print(listOfStrs);

	return 0;

}

Output:
is , of , the , Hi , Hello , from , 
from , Hello , Hi , the , of , is , 
is , of , the , Hi , Hello , from , 
the , of , is , Hi , Hello , from ,