This post will discuss how to print a std::list in C++.

Lists are sequence containers that are implemented as a doubly linked list and allow iteration in both directions and take O(1) time for insertion and deletion. They are usually slower than other standard sequence containers (arrays or vectors) to retrieve any item.

There are many ways to print a list in C++, which are covered below:

1. Using range-based for-loop

The recommended approach is to use the range-based for-loop to print elements in the list container. Please note that this will only work with C++11, and later, with C++98, we can use iterators.

Download  Run Code

Output:

blue
red
green

2. Using std::copy function

Another 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:

blue
red
green

 
With C++17, we can use std::copy with std::experimental::ostream_joiner which is 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:

blue
red
green

3. Using std::for_each function

We can also use the std::for_each STL algorithm, which 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:

blue
red
green

4. Using Iterator

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:

blue
red
green

5. 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:

blue
red
green

That's all about printing a std::list in C++.