template<class InputIt1, class InputIt2, class OutputIt>
OutputIt set_symmetric_difference(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first);
Parameters
Parameter
Description
first1, last1
Required. The first sorted range.
first2, last2
Required. The second sorted range.
d_first
Required. Where the result is written.
comp
Optional. The comparison both ranges were sorted with.
Return Value
Return Value
Description
Iterator
Points just after the last element written in the destination.
C++ Examples
Example 1 — Items in only one list
Find what the two vectors do not share.
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> a = {1, 2, 3, 4};
std::vector<int> b = {3, 4, 5, 6};
std::vector<int> out;
std::set_symmetric_difference(a.begin(), a.end(), b.begin(), b.end(),
std::back_inserter(out));
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
1 2 5 6
How It Works
3 and 4 appear in both vectors, so they are left out.
1 and 2 are only in a. 5 and 6 are only in b.
The result holds all four, in sorted order.
Example 2 — Repeated values
Only the extra copies are kept.
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> a = {1, 2, 2};
std::vector<int> b = {2, 3};
std::vector<int> out;
std::set_symmetric_difference(a.begin(), a.end(), b.begin(), b.end(),
std::back_inserter(out));
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
1 2 3
How It Works
a has two 2s and b has one. One pair cancels.
One extra 2 from a is left.
With 1 and 3 that gives 1, 2 and 3.
Example 3 — Equal ranges
Identical data leaves nothing.
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {1, 2, 3};
std::vector<int> out;
std::set_symmetric_difference(a.begin(), a.end(), b.begin(), b.end(),
std::back_inserter(out));
if (out.empty()) {
std::cout << "No differences\n";
}
return 0;
}
Output
No differences
How It Works
Every element of a has a partner in b.
All pairs cancel, so nothing is written.
out.empty() is true.
Frequently Asked Questions
In C++, std::set_symmetric_difference() builds the symmetric difference of two sorted ranges: elements in exactly one of them. Include <algorithm> to use it.
Include <algorithm>. It has been part of C++ since C++98, so every modern compiler supports it.
It returns an iterator to the position after the last element written in the destination.
set_difference() keeps what is only in the first range. The symmetric version keeps what is only in either range.
Nothing is written, so the destination stays empty.