Convert a vector to a set in C++
This post will discuss how to convert a vector to a set in C++.
1. Naive Solution
We can also write our own routine for converting a vector to a set. The idea is very simple – create an empty set, traverse the vector using a range-based for-loop and insert each encountered element into the set.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <unordered_set> int main() { std::vector<int> input({ 1, 2, 2, 1, 3, 1, 4 }); std::unordered_set<int> set; for (const int &i: input) { set.insert(i); } for (const int &i: set) { std::cout << i << " "; } return 0; } |
Output:
4 3 2 1
2. Using Range Constructor
An efficient solution is to pass two input iterators pointing to the beginning and end of the given vector to the constructor of the set class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <vector> #include <unordered_set> int main() { std::vector<int> input({ 1, 2, 2, 1, 3, 1, 4 }); std::unordered_set<int> set(input.begin(), input.end()); for (const int &i: set) { std::cout << i << " "; } return 0; } |
Output:
4 3 2 1
3. Using std::copy function
If we need to copy the vector elements to an existing set, the recommended approach is to use the standard algorithm std::copy defined in the <algorithm> header.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <algorithm> #include <unordered_set> int main() { std::vector<int> input({ 1, 2, 2, 1, 3, 1, 4 }); std::unordered_set<int> set; std::copy(input.begin(), input.end(), std::inserter(set, set.end())); for (const int &i: set) { std::cout << i << " "; } return 0; } |
Output:
4 3 2 1
That’s all about converting a vector 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 :)