Initialize a std::set or std::unordered_set in C++
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 '{...}'.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <unordered_set> int main() { std::unordered_set<int> s { 10, 20, 30 }; for (auto i: s) { std::cout << i << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <set> // Binary predicate struct comp { template<typename T> bool operator()(const T &l, const T &r) const { return l > r; } }; int main() { // The elements are sorted according to the comparison object std::set<int, comp> ints = { 10, 20, 30 }; for (auto i: ints) { std::cout << i << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <unordered_set> int main() { std::unordered_set<int> v = { 10, 20, 30 }; // copy constructor std::unordered_set<int> s(v); for (auto i: s) { std::cout << i << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <unordered_set> int main() { int arr[] = { 10, 20, 30 }; std::unordered_set<int> s(std::begin(arr), std::end(arr)); // or do initialize like this // std::unordered_set<int> s(arr, arr + sizeof(arr)/sizeof(int)); for (auto i: s) { std::cout << i << std::endl; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <unordered_set> int main() { std::unordered_set<int> s; for (auto i: s) { std::cout << i << std::endl; } return 0; } |
Output:
The standard output is empty
That’s all about initializing a std::set or std::unordered_set in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)