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:

Download  Run Code

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.

Download  Run Code

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:

Download  Run Code

Output:

A B C D

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