Merge multiple sets in C++
This post will discuss how to merge multiple sets in C++.
1. Using std::set::insert
The recommended solution to insert elements from one set to another set is using the std::set::insert function. It can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <set> int main() { std::set<char> s1 = { 'A', 'B', 'C' }; std::set<char> s2 = { 'D', 'E' }; s1.insert(s2.begin(), s2.end()); for (const auto &val: s1) { std::cout << val << ' '; } return 0; } |
Output:
A B C D E
2. Using std::set_union
The above solution adds the contents of a set to another set. To get a new set containing elements from both sets, consider using the std::set_union standard algorithm from header <algorithm>. It accepts an iterator to the initial and final positions of two sorted ranges, and the output iterator to the destination and fills the destination with the union of the specified sorted ranges. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <set> #include <algorithm> int main() { std::set<char> s1 = { 'A', 'B', 'C' }; std::set<char> s2 = { 'D', 'E' }; std::set<char> s; std::set_union(std::begin(s1), std::end(s1), std::begin(s2), std::end(s2), std::inserter(s, std::begin(s))); for (const auto &val: s) { std::cout << val << ' '; } return 0; } |
Output:
A B C D E
3. Using std::merge function
Starting with C++17, we can use the merge() function of std::set directly to merge elements of a set to another set. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <set> int main() { std::set<char> s1 = { 'A', 'B', 'C' }; std::set<char> s2 = { 'D', 'E' }; s1.merge(s2); for (const auto &val: s1) { std::cout << val << ' '; } return 0; } |
Output:
A B C D E
That’s all about merging multiple sets 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 :)