Open In App

How to Concatenate Two Sets in C++?

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, sets are the data containers that store the unique elements in some specified order. Concatenating two sets means merging the elements of two sets into the first set. In this article, we will learn how to concatenate two sets in C++ STL.

Example

Input:
mySet1 = {1, 2, 3, 4, 5, 8, 9}
mySet2 = {1, 5, 6, 8, 9, 11, 12, 13}

Output:
result: {1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 13}

Merge Two Sets in C++

To concatenate two sets in C++, we can use the std::set_union function provided in the STL <algorithm> library that finds the union of two sorted ranges and stores it in some other container. After that, we can replace the content of the first set with the resulted container.

Syntax of std::set_union()

set_union (first1, last1, first2, last2, result);

where,

  • first1: Iterator to the beginning of the first range.
  • last1: Iterator to the last of the first range.
  • first2: Iterator to the beginning of the second range.
  • last1: Iterator to the last of the second range.
  • result: Iterator to the beginning of the resulant data container.

Note: The order of the element in the result set will be according to the specified order in the declaration. Also, no duplicates will be added even if they both occur in the two sets.

stores

C++ Program to Concatenate Two Sets

C++




// C++ Program to Concatenate two sets
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
  
// Driver Code
int main()
{
    set<int> set1 = { 1, 2, 3, 4 }; // Set 1
    set<int> set2 = { 3, 4, 5, 6 }; // Set 2
  
    set<int> result;
    
    // Concanate
    set_union(set1.begin(), set1.end(), set2.begin(),
              set2.end(), inserter(result, result.begin()));
  
    set1 = result;
  
    cout << "Concatenated Set: ";
    for (const auto& element : set1) {
        cout << element << " ";
    }
    return 0;
}


Output

Concatenated Set: 1 2 3 4 5 6 

Time Complexity: O(N*logN + MlogM), where M and N is the size of two vectors.
Space Complexity: O(N + M)

In C++ STL, you can also concatenate two sets using the insert function.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads