Implement Set Difference in C++ STL



The Set Difference is an operation used to find all elements present in the first set but not in the second. In this article, we will learn how to use the set_difference algorithm from the Standard Template Library (STL) in C++ to find the difference of two sets.

What is Set Difference?

The set difference is an arithmetic operation performed between two sets to find all elements present in the first set but not in the second. In C++, we have set_difference which is a built-in algorithm provided by C++ STL that computes the set difference of two sorted ranges of sets. That is, it returns the elements that are in the first range but not in the second. The input ranges must be sorted in ascending order.

For example, consider the following sets:

Set A = {1, 2, 3, 4} Set B = {2, 4, 6} Difference A - B = {1, 3}

Using set_difference Function in STL

The set_difference function is defined in the <algorithm> header of STL. Below are some points about this algorithm:

  • Header: <algorithm>
  • Syntax:
    set_difference(start1, end1, start2, end2, result_iterator);
  • Parameters:
  • start1, end1: Start and end iterators of the first sorted range.
  • start2, end2: Start and end iterators of the second sorted range.
  • result_iterator: Iterator to the beginning of the destination range.

Steps to Implement set_difference in C++ STL

Following are steps/algorithm to use set_difference using C++ STL:

  • Include the <algorithm> and <vector> header files.
  • Define and initialize two sorted vectors (or sets).
  • Use set_difference() to find elements in first range not present in second.
  • Store the result in another vector or print directly using output iterator.

C++ Program to Implement set_difference using STL

The below code is the implementation of the above algorithm in C++ language.

Open Compiler
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> A = {1, 2, 3, 4}; vector<int> B = {2, 4, 6}; vector<int> result; // Compute set difference A - B set_difference(A.begin(), A.end(), B.begin(), B.end(), back_inserter(result)); cout << "Elements in A but not in B: "; for (int x : result) { cout << x << " "; } cout << endl; return 0; }

The output of above code will be

Elements in A but not in B: 1 3

Time and Space Complexity

Time Complexity:

  • set_difference: O(n), where n is the sum of the sizes of both input ranges.

Space Complexity: O(n), where n is the size of the result range.

Updated on: 2025-05-12T19:45:32+05:30

866 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements