Lists are sequence containers that are implemented as a doubly linked list and allow iteration in both directions. This post will discuss how to print a list in reverse order in C++.

1. Using std::copy function

An elegant solution is to use std::copy to copy the list’s contents to the output stream (in this case std::cout) with the help of the output iterator std::ostream_iterator.

Download  Run Code

Output:

z y x

 
Starting C++17, we can use std::experimental::ostream_joiner defined in header <experimental/iterator>. It is a single-pass output iterator which can write successive objects into the std::cout, using the << operator, separated by a delimiter between every two objects.

Run Code

Output:

z y x

2. Using std::for_each function

We can also use the std::for_each algorithm that accepts an input range defined by two iterators and applies a specified function on each element in that range. The specified function may be a unary function, or an object of a class overloading the () operator or a lambda expression.

Download  Run Code

Output:

z y x

3. Using Iterators

We can also use the iterators to print a list. Since we’re not modifying the contents of the list inside the while loop, consider using the const_iterator, which is returned by cbegin() and cend(). Before C++11, we can use begin() and end().

Download  Run Code

Output:

z y x

4. Overloading << Operator

The output streams (such as cout) use the insertion (<<) operator, which can be overloaded to accept a list object. We basically need to overload the << operator to recognize an ostream object on the left and a list object on the right.

Download  Run Code

Output:

z y x

That's all about printing a list in reverse order in C++.