Merge multiple sets elements in a single set

C++StlSet

C++ Problem Overview


I would like to know if there is any std library or boost tool to easily merge the contents of multiple sets into a single one.

In my case I have some sets of ints which I would like to merge.

C++ Solutions


Solution 1 - C++

You can do something like:

std::set<int> s1;
std::set<int> s2;
// fill your sets
s1.insert(s2.begin(), s2.end());

Solution 2 - C++

Looks like you are asking for std::set_union.

Example:

#include <set>
#include <algorithm>

std::set<int> s1; 
std::set<int> s2; 
std::set<int> s3;

// Fill s1 and s2 

std::set_union(std::begin(s1), std::end(s1),
               std::begin(s2), std::end(s2),                  
               std::inserter(s3, std::begin(s3)));

// s3 now contains the union of s1 and s2

Solution 3 - C++

With C++17, you can use merge function of set directly.

This is better, when you want the set2 elements extracted & inserted into set1 as part of merging.

Like below:

set<int> set1{ 1, 2, 3 };
set<int> set2{ 1, 4, 5 };

// set1 has     1 2 3		set2 has     1 4 5
set1.merge(set2);
// set1 now has 1 2 3 4 5	set2 now has 1   (duplicates are left in the source, set2)

Solution 4 - C++

look what std::merge can do for you

cplusplus.com/reference/algorithm/merge

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodeJackView Question on Stackoverflow
Solution 1 - C++Nicola MusattiView Answer on Stackoverflow
Solution 2 - C++Antonio PérezView Answer on Stackoverflow
Solution 3 - C++Manohar Reddy PoreddyView Answer on Stackoverflow
Solution 4 - C++NelstaarView Answer on Stackoverflow