CKTIS / C++
std::set_symmetric_difference — symmetric difference of sorted ranges
std::set_symmetric_difference writes the sorted symmetric difference of two sorted ranges. It accounts for duplicate counts, accepts an output iterator, and returns an iterator past the elements written.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
std::set_symmetric_difference(first1, last1, first2, last2, result);
std::set_symmetric_difference(first1, last1, first2, last2, result, comp);std::set_symmetric_difference, declared in <algorithm>, copies the symmetric difference of [first1, last1) and [first2, last2) to result. For duplicate-free data, these are the elements present in exactly one range. The algorithm operates on iterator ranges; it does not require a std::set container.
Both inputs must be sorted under the same ordering: ascending by default, or according to the comparator in the overload taking comp. comp must define a strict weak ordering. Equivalence means !comp(a, b) && !comp(b, a), not necessarily a == b. The output is sorted as well.
Duplicates are not simply removed: for m and n equivalent elements, the output contains |m-n| elements. These are the final excess elements from the range with more occurrences, preserving their order. In contrast, ordinary difference with std::set_difference is one-sided.
The output region must not overlap either input. Provide enough writable positions or use std::back_inserter with a separate vector; reserve() alone does not create elements writable through begin(). The returned iterator points just past the last element written. The comparison count is linear in the combined input lengths.
Examples
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
const std::vector<int> a{1, 2, 2, 4};
const std::vector<int> b{2, 3, 4, 4};
std::vector<int> result;
std::set_symmetric_difference(
a.begin(), a.end(), b.begin(), b.end(),
std::back_inserter(result));
for (std::size_t i = 0; i < result.size(); ++i) {
if (i != 0) std::cout << ' ';
std::cout << result[i];
}
std::cout << '\n';
}
Result
1 2 3 4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.