This post will discuss how to merge elements of the two given sets into a new set container in C++. Since all elements in a set are distinct, the common elements in both input sequences are discarded in the destination set.

1. Using std::set::insert function

We can use the public member function std::set::insert of the std::unordered_set or std::set container for inserting elements from a set to another set.

Here’s a C++11 version that uses a copy constructor for copying elements of the first set into the result set and then calls insert() on the result set to insert elements of the second set. We can easily modify code to avoid copy constructor and use only insert() to insert elements of both the sets.

Download  Run Code

Output:

1 2 3 4 5 6

2. Using std::set_union function

Another good alternative is to use the std::set_union that performs union operation on two sorted sequences. It takes input iterators to the initial and final positions of both sequences and output iterator to the initial position of the destination range. The specified comparator decides the ordering of elements in the destination range. If no comparator is specified, the elements are compared using default operator<.

Download  Run Code

Output:

1 2 3 4 5 6

3. Using std::merge function

The recommended approach uses the std::merge that combines the elements of two sorted sequences according to the specified comparator or operator<. Like std::set_union, it takes input iterators to the initial and final positions of input sequences and output iterator to the initial position of the destination sequence.

Download  Run Code

Output:

1 2 3 4 5 6

That’s all about merging two sets using std::set_union and std::merge in C++.