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:

Download  Run Code

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:

Download  Run Code

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:

Download Code

Output:

A B C D E

That’s all about merging multiple sets in C++.