C++ std::set_symmetric_difference

The algorithm std::set_symmetric_difference function computes the symmetric difference between two sorted ranges and stores the result in a destination range. The symmetric difference contains all elements that are in either of the ranges, but not in both. Both input ranges must be sorted according to the same criteria for the function to work correctly.


Syntax of std::set_symmetric_difference

</>
Copy
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1,
                                         InputIterator2 first2, InputIterator2 last2,
                                         OutputIterator result);

template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1,
                                         InputIterator2 first2, InputIterator2 last2,
                                         OutputIterator result, Compare comp);

Parameters of std::set_symmetric_difference

ParameterDescription
first1, last1Input iterators defining the first sorted range.
first2, last2Input iterators defining the second sorted range.
resultOutput iterator to the beginning of the destination range where the result is stored.
comp (optional)A binary comparison function that defines the order of elements. Defaults to <.

Return Value of std::set_symmetric_difference

Returns an iterator to the end of the destination range containing the symmetric difference of the two input ranges.


Examples for std::set_symmetric_difference

Example 1: Basic Usage of std::set_symmetric_difference

This example demonstrates finding the symmetric difference between two sorted vectors:

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> set1 = {1, 3, 5, 7};
    std::vector<int> set2 = {3, 5, 6, 8};
    std::vector<int> result(set1.size() + set2.size());

    auto it = std::set_symmetric_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), result.begin());

    result.resize(it - result.begin()); // Adjust size to remove unused elements

    std::cout << "Symmetric difference of sets: ";
    for (int n : result) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. Include necessary headers:
    • <iostream>: Used for input/output operations.
    • <algorithm>: Includes the std::set_symmetric_difference function.
    • <vector>: Used for the std::vector container.
  2. Initialize two sorted sets:
    • set1: A vector containing {1, 3, 5, 7}.
    • set2: A vector containing {3, 5, 6, 8}.
    • Both vectors must be sorted in ascending order for std::set_symmetric_difference to work correctly.
  3. Prepare a result vector:
    • A vector named result is initialized with a size large enough to hold all possible elements from the symmetric difference of set1 and set2. This size is the sum of their sizes.
  4. Perform the symmetric difference operation:
    • The function std::set_symmetric_difference calculates the elements that are in either set1 or set2, but not in both.
    • It takes five arguments:
      • set1.begin(): Iterator pointing to the beginning of set1.
      • set1.end(): Iterator pointing to the end of set1.
      • set2.begin(): Iterator pointing to the beginning of set2.
      • set2.end(): Iterator pointing to the end of set2.
      • result.begin(): Iterator pointing to the beginning of the result vector, where the symmetric difference elements will be stored.
    • The function returns an iterator pointing to the end of the resulting range in the result vector.
  5. Resize the result vector:
    • The size of the result vector is adjusted to remove unused elements using result.resize(it - result.begin()).
  6. Output the symmetric difference of the sets:
    • The program uses a for loop to iterate over the elements in the result vector and prints them separated by spaces.
    • The output is: "Symmetric difference of sets: 1 6 7 8", as these are the elements that are in either set1 or set2, but not in both.

Output:

Symmetric difference of sets: 1 6 7 8

Example 2: Using a Custom Comparison Function for std::set_symmetric_difference

This example demonstrates finding the symmetric difference of two sorted ranges in descending order using a custom comparison function:

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>

bool descending(int a, int b) {
    return a > b;
}

int main() {
    std::vector<int> set1 = {7, 5, 3, 1};
    std::vector<int> set2 = {8, 6, 5, 3};
    std::vector<int> result(set1.size() + set2.size());

    auto it = std::set_symmetric_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), result.begin(), descending);

    result.resize(it - result.begin()); // Adjust size to remove unused elements

    std::cout << "Symmetric difference of sets in descending order: ";
    for (int n : result) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

Symmetric difference of sets in descending order: 8 7 6 1

Exception Handling in std::set_symmetric_difference

The std::set_symmetric_difference function does not throw exceptions on its own. However, the comparison function passed as an argument may throw exceptions, which can be caught and handled appropriately.

Example 1: Exception in Custom Comparison Function

This example demonstrates how exceptions in a custom comparison function are handled:

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>
#include <stdexcept>

bool faulty_compare(int a, int b) {
    if (a == 5 || b == 5) {
        throw std::runtime_error("Comparison involving 5 is not allowed.");
    }
    return a < b;
}

int main() {
    std::vector<int> set1 = {1, 3, 5, 7};
    std::vector<int> set2 = {3, 5, 6, 8};
    std::vector<int> result(set1.size() + set2.size());

    try {
        auto it = std::set_symmetric_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), result.begin(), faulty_compare);

        result.resize(it - result.begin()); // Adjust size to remove unused elements

        std::cout << "Symmetric difference of sets: ";
        for (int n : result) {
            std::cout << n << " ";
        }
        std::cout << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output:

Exception caught: Comparison involving 5 is not allowed.