Convert a set to a vector in C++
This post will discuss how to convert a set to a vector in C++.
1. Using Range Constructor
The most elegant solution is to use the std::vector range constructor, which takes two input iterators pointing to the beginning and the end of an input sequence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <set> #include <vector> #include <algorithm> int main() { std::set<char> s = { 'a', 'b', 'c', 'd', 'e' }; std::vector<char> v(s.begin(), s.end()); for (char const &c: v) { std::cout << c << ' '; } return 0; } |
Output:
a b c d e
2. Using std::copy function
Another good alternative is to use the std::copy, which inserts elements from a source container into a destination container. The destination container should be large enough to accommodate all elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <set> #include <vector> #include <algorithm> int main() { std::set<char> s = { 'a', 'b', 'c', 'd', 'e' }; std::vector<char> v(s.size()); std::copy(s.begin(), s.end(), v.begin()); for (char const &c: v) { std::cout << c << ' '; } return 0; } |
Output:
a b c d e
We can also pass a std::back_inserter to std::copy. This works fine on an empty container as it creates an output iterator that calls push_back on the destination container for each array element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <set> #include <vector> #include <algorithm> int main() { std::set<char> s = { 'a', 'b', 'c', 'd', 'e' }; std::vector<char> v; std::copy(s.begin(), s.end(), std::back_inserter(v)); for (char const &c: v) { std::cout << c << ' '; } return 0; } |
Output:
a b c d e
3. Using std::vector::assign function
One can also use vector::assign that replaces the current contents of the vector with each of the elements in the specified range.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <set> #include <vector> #include <algorithm> int main() { std::set<char> s = { 'a', 'b', 'c', 'd', 'e' }; std::vector<char> v; v.assign(s.begin(), s.end()); for (char const &c: v) { std::cout << c << ' '; } return 0; } |
Output:
a b c d e
That’s all about converting a set to a vector 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 :)