This post will discuss how to print a std::set or std::unordered_set in C++.

1. Using std::copy function

The idea is to copy the set’s contents to the output stream (which happens to be std::cout here) by using std::copy, which takes an output iterator std::ostream_iterator.

Download  Run Code

Output:

1 5 3 2 4

 
From C++17 onwards, we can use std::experimental::ostream_joiner defined in <experimental/iterator> header.

Run Code

Output:

1 4 2 3 5

2. Using range-based for-loop

The recommended approach in C++11 is to use the new range-based for-loops for printing the set elements.

Download  Run Code

Output:

1 5 3 2 4

3. Using std::for_each function

Another elegant solution is to use std::for_each, which takes a range defined by two input iterators and applies a function on every element in that range. The function can be a unary function, or an object of a class overloading the () operator or a lambda expression.

Download  Run Code

Output:

1 5 3 2 4

4. Using Iterator

We can also use iterators to iterate a set and print its contents. Also, from C++11 onwards, it is recommended to use the constant iterators to not modify the set’s contents inside the loop.

Download  Run Code

Output:

1 5 3 2 4

5. Overloading << Operator

To get std::cout to accept any set object after the insertion (<<) operator, we can overload the << operator to recognize an ostream object on the left and a set object on the right, as shown below:

Download  Run Code

Output:

1 5 3 2 4

That's all about printing a std::set or std::unordered_set in C++.