Convert a std::list to std::set or std::unordered_set in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <unordered_set> #include <list> int main() { std::list<int> list = { 1, 2, 3 }; std::unordered_set<int> s; for (int const &i: list) { s.insert(i); } for (int const &i: s) { std::cout << i << ' '; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <list> #include <unordered_set> #include <algorithm> int main() { std::list<int> list = { 1, 2, 3 }; std::unordered_set<int> s(std::begin(list), std::end(list)); for (int const &i: s) { std::cout << i << ' '; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <unordered_set> #include <list> int main() { std::list<int> list = { 1, 2, 3 }; std::unordered_set<int> s; std::copy(list.begin(), list.end(), std::inserter(s, s.begin())); for (int const &i: s) { std::cout << i << ' '; } return 0; } |
Output:
3 2 1
That’s all about converting a std::list to std::set or std::unordered_set in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)