This post will discuss how to initialize a set in C++.

There are several approaches to initialize a std::set or std::unordered_set in C++, as shown below:

1. Using Initializer List

In C++11 and above, we can use the initializer lists '{...}' to initialize a set. This won’t work in C++98 as the standard allows set to be initialized by a constructor and not by '{...}'.

Download  Run Code

Output:

30
10
20

 
We can also pass a comparison object with std::set, which is a binary predicate taking two elements of the same type and defining the set order. It returns true if the first parameter appears before the second parameter and false otherwise.

Download  Run Code

Output:

30
20
10

2. Using Copy Constructor

We can use a copy constructor to initialize the set from elements of another set, following the same order of elements.

Download  Run Code

Output:

30
10
20

3. Using Range Constructor

We can use a range constructor to initialize the set from elements of an array or another container of the same type.

Download  Run Code

Output:

30
10
20

4. Using Default Constructor

We can use the empty container constructor (or a default constructor) to construct an empty set (with no elements), as shown below:

Download  Run Code

Output:

The standard output is empty

That’s all about initializing a std::set or std::unordered_set in C++.