This post will discuss how to convert an array to a set in C++.

1. Naive Solution

A naive solution is to use a range-based for-loop (introduced in C++11) to insert all the array elements into the set using the insert() function. We can also use a simple for-loop for this.

Download  Run Code

Output:

5 1 2 3 4

2. Using Range Constructor

An efficient solution is to use the set’s range constructor to initialize the set from elements of the specified range.

Download  Run Code

Output:

5 1 2 3 4

 
In C++11, we can avoid calculating the array’s size by calling std::begin and std::end functions, which return an iterator to the beginning and end of the array, respectively.

Download  Run Code

Output:

5 1 2 3 4

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