Transform a vector to a set in C++
This post will discuss how to transform a vector to a set in C++.
A simple solution to transform a vector to a set is using the std::set range constructor. It can accept iterator to the initial and final positions of a vector and constructs a set container with elements of the range. The following program demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <vector> #include <set> int main() { std::vector<char> v = { 'A', 'B', 'C', 'D' }; std::set<char> s(v.begin(), v.end()); for (const auto &val: s) { std::cout << val << ' '; } return 0; } |
Output:
A B C D
The above solution copies all elements from a vector to a set. Instead of copying each element, we can actually move each element from a vector to a set using the move iterator std::make_move_iterator, available with C++11.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <set> int main() { std::vector<char> v = { 'A', 'B', 'C', 'D' }; std::set<char> s(std::make_move_iterator(v.begin()), std::make_move_iterator(v.end())); // vector now contains unspecified values; clear it: v.clear(); for (const auto &val: s) { std::cout << val << ' '; } return 0; } |
Output:
A B C D
We can also write custom logic for transforming a vector into a set. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <set> int main() { std::vector<char> v = { 'A', 'B', 'C', 'D' }; std::set<char> s; for (const auto &i: v) { s.insert(i); } for (const auto &i: s) { std::cout << i << ' '; } return 0; } |
Output:
A B C D
That’s all about transforming 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 :)