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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

Output:

4 3 2 1

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