Use set_symmetric_difference()
, but before this the source ranges must be ordered:
vector<int> v1;
vector<int> v2;
// ... Populate v1 and v2
// For the set_symmetric_difference algorithm to work,
// the source ranges must be ordered!
vector<int> sortedV1(v1);
vector<int> sortedV2(v2);
sort(sortedV1.begin(),sortedV1.end());
sort(sortedV2.begin(),sortedV2.end());
// Now that we have sorted ranges (i.e., containers), find the differences
vector<int> vDifferences;
set_symmetric_difference(
sortedV1.begin(), sortedV1.end(),
sortedV2.begin(), sortedV2.end(),
back_inserter(vDifferences));
After this, all different elements of these two vectors (i.e. either in v1
or v2
, but not both) will be stored in vector<int> vDifferences
. For your example, it will be {0, 2, 6}
.
[...] Computes symmetric difference of two sorted ranges: the elements that are found in either of the ranges, but not in both of them are copied to the range beginning at d_first. The resulting range is also sorted. [...]
If you just need the missing elements in the v1
, you can further scan this vDifferences
against sortedV1
to find them out.
Check out this discussion for more info.