Initialize a std::set or std::unordered_set in C++

In this post, we will see how to initialize a set in C++.


 

There are several approach 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 initializer lists '{...}' for initializing a set. This won’t work in C++98 as 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 defines the set ordering. 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 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 set from elements of an array or another container of 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:

Standard output is empty

 

 
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 🙂
 


Get great deals at Amazon




Categories

Leave a Reply

Notify of
avatar
wpDiscuz