This post will discuss how to convert a std::list to std::set or std::unordered_set in C++.

1. Naive Solution

A simple solution is to loop through the list and individually add each element to an empty set.

Download  Run Code

Output:

3 2 1

2. Using Range Constructor

The recommended solution is to use the range constructor offered by the set class that accepts input iterators pointing to the beginning and the end of an input sequence.

Download  Run Code

Output:

3 1 2

3. Using std::copy function

We can even use the standard algorithm std::copy, which copies the elements from the specified range to another container.

The following code uses std::inserter to constructs a std::insert_iterator for the set container as std::back_inserter and std::front_inserter do not work on sets.

Download  Run Code

Output:

3 2 1

That’s all about converting a std::list to std::set or std::unordered_set in C++.