Convert an array to a set in C++
This post will discuss how to convert an array to a set in C++.
1. Naive Solution
A naive solution is to use a range-based for-loop (introduced in C++11) to insert all the array elements into the set using the insert() function. We can also use a simple for-loop for this.
|
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 A[] = { 1, 2, 3, 4, 5 }; std::unordered_set<int> s; for (int i: A) { s.insert(i); } for (int i: s) { std::cout << i << " "; } return 0; } |
Output:
5 1 2 3 4
2. Using Range Constructor
An efficient solution is to use the set’s range constructor to initialize the set from elements of the specified range.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <unordered_set> int main() { int A[] = { 1, 2, 3, 4, 5 }; int n = sizeof(A) / sizeof(A[0]); std::unordered_set<int> s(A, A + n); for (int i: s) { std::cout << i << " "; } return 0; } |
Output:
5 1 2 3 4
In C++11, we can avoid calculating the array’s size by calling std::begin and std::end functions, which return an iterator to the beginning and end of the array, respectively.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <unordered_set> int main() { int A[] = { 1, 2, 3, 4, 5 }; std::unordered_set<int> s(std::begin(A), std::end(A)); for (int i: s) { std::cout << i << " "; } return 0; } |
Output:
5 1 2 3 4
That’s all about converting an array to a 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 :)