Open In App

How to Find the Difference of Two Sets in C++?

In C++, the set container provides an efficient way to store unique elements in sorted order. Finding the difference between two sets involves determining the elements that are present in one set but not in the other. In this article, we are going to learn how to find the difference of two sets in C++ STL.

Example:



Input: 
set1 = {1, 2, 3, 4, 5};
set2 = {3, 4, 5, 6, 7};

Output: 
Difference of Two Sets: 1 2

Set Difference in C++

To find the difference between the two std::set, we can use the std::set_difference function from the <algorithm> library that takes two sorted ranges as input and produces a sorted range that contains the elements present in the first range but not in the second range.

Syntax of std::set_difference

set_difference( first1, last1, first2, last2, d_first );

C++ Program to Find the Difference of Two Sets

The below example demonstrates how we can find the difference between two sets using set_difference in C++ STL.






// C++  Program to illustrate how to find the difference of
// two sets
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
  
    // creating two sets
    set<int> set1 = { 1, 2, 3, 4, 5 };
    set<int> set2 = { 3, 4, 5, 6, 7 };
  
    // initilize difference set to store difference
    set<int> difference;
  
    // Use set_difference to find difference
    set_difference(
        set1.begin(), set1.end(), set2.begin(), set2.end(),
        inserter(difference, difference.begin()));
  
    // Print the difference
    cout << "Set after Difference: ";
    for (auto const& elem : difference) {
        cout << elem << " ";
    }
    cout << endl;
  
    return 0;
}

Output
Set after Difference: 1 2 

Time Complexity: O(N), where N is the size of set1.
Auxiliary Space: O(N)


Article Tags :