Convert an array to a set in C++

In this post, we will discuss how to convert an array to a set in C++.

 

1. Naive

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

 

Download   Run Code

Output:

5 1 2 3 4

 

2. Range Constructor

Efficient solution would be to use 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 size of the array by calling std::begin and std::end methods which returns iterator to the beginning and end of the array respectively.

 

Download   Run Code

Output:

5 1 2 3 4

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Categories

Leave a Reply

Notify of
avatar
wpDiscuz