Implement Set Symmetric Difference in C++ STL



The Set Symmetric Difference is an operation used to find all elements that are present in either of the sets but not in both. In this article, we will learn how to use the set_symmetric_difference algorithm from the Standard Template Library (STL) in C++ to find the symmetric difference of two sets.

What is Set Symmetric Difference?

The set symmetric difference is an arithmetic operation performed between two sets to find all elements that are present in either of the sets but not in both. In C++, we have set_symmetric_difference(), which is a built-in function provided by C++ STL that computes the symmetric difference of two sorted ranges of sets. That is, it returns the elements that are in one range or the other, but not in both. 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}

Symmetric Difference A ? B = {1, 3, 6}

Using set_symmetric_difference Function in STL

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

  • Header: <algorithm>
  • Syntax:
    set_symmetric_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_symmetric_difference in C++ STL

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

  • Include the <algorithm> and <vector> header files.
  • Define and initialize two sorted vectors (or sets).
  • Use set_symmetric_difference() function to find elements that are in either of the sets but not in both.
  • Store the result in another vector or print directly using output iterator.

C++ Program to Implement set_symmetric_difference using STL

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

#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 symmetric difference A ? B
    set_symmetric_difference(A.begin(), A.end(), B.begin(), B.end(), back_inserter(result));

    cout << "Elements in A or B but not in both: ";
    for (int x : result) {
        cout << x << " ";
    }
    cout << endl;

    return 0;
}

The output of above code will be

Elements in A or B but not in both: 1 3 6

Time and Space Complexity

Time Complexity:

  • set_symmetric_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:08+05:30

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements