使用 set_symmetric_difference(),但在此之前必须对源范围进行排序:
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));
在此之后,这两个向量的所有不同元素(即在v1 或v2 中,但不能同时在两者中)将存储在vector<int> vDifferences 中。对于您的示例,它将是 {0, 2, 6}。
[...] 计算两个排序范围的对称差:在任一范围内找到但不在这两个范围内的元素被复制到从 d_first 开始的范围内。结果范围也被排序。 [...]
如果您只需要v1 中缺少的元素,您可以进一步扫描此vDifferences 与sortedV1 以找出它们。
查看this discussion 了解更多信息。