Print a std::list in C++

In this post, we will see how to print a std::list in C++.


 

Lists are sequence containers which are implemented as doubly linked list and allows iteration in both directions and takes O(1) time for insertion and deletion. They are usually slower than other standard sequence containers (arrays or vectors) for retrieval of any item.

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

 

1. C++11 – 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. std::copy

Another elegant solution would be to use std::copy to copy the contents of the list 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 << operator, separated by a delimiter between every two objects.

 

Run Code

Output:

blue
red
green

 

3. std::for_each

We can also use 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. 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

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding :)
 






Leave a Reply

avatar
  Subscribe  
Notify of