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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

Output:

a b c d e

That’s all about converting a set to a vector in C++.