场景:
1.需要合并集合或过滤出不同集合里的元素便于操作.如一个集合里有索引值1,2.总集合里有1,2,3,4,5.需要找出3,4,5时,就需要set_symmetric_difference
#include <stdio.h> #include <string.h> #include <algorithm> #include <vector> #include <iostream> #include <string> using namespace std; //1.可重复值 //2.集合对称差 void ExampleSetSymmetricDifference() { vector<int> i1; vector<int> i2; // int i1[] = {1,2,5,7}; // int i2[] = {0,1,2,3}; // int i2[] = {0,1,2,3,4,5,6,7}; std::vector<int>::iterator it; i1.push_back(1); i1.push_back(2); i1.push_back(5); i1.push_back(8); i2.push_back(0); i2.push_back(1); i2.push_back(2); i2.push_back(3); i2.push_back(4); i2.push_back(5); i2.push_back(6); i2.push_back(6); i2.push_back(7); sort(i1.begin(),i1.end()); sort(i2.begin(),i2.end()); vector<int> res(i2.size()+i1.size()); //对称差 it = set_symmetric_difference(i1.begin(),i1.end(),i2.begin(),i2.end(),res.begin()); res.resize(it-res.begin()); size_t size = res.size(); printf("size %d\n",size); for (it=res.begin(); it!=res.end(); ++it) { std::cout << ' ' << *it; } std::cout << std::endl; } //1.可重复值 //2.集合差集 void ExampleSetDifference() { int first[] = {5,10,15,15,25}; int second[] = {50,40,30,20,10}; std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0 std::vector<int>::iterator it; std::sort (first,first+5); // 5 10 15 20 25 std::sort (second,second+5); // 10 20 30 40 50 //frist相对second的不同值 it=std::set_difference (first, first+5, second, second+5, v.begin()); // 5 15 25 0 0 0 0 0 0 0 v.resize(it-v.begin()); // 5 15 25 std::cout << "The difference has " << (v.size()) << " elements:\n"; for (it=v.begin(); it!=v.end(); ++it) { std::cout << ' ' << *it; } std::cout << std::endl; } //1.可重复值 //1.集合并集,共有的只出现一次 void ExampleSetUnion() { int first[] = {5,10,15,15,25}; int second[] = {50,40,30,20,10}; std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0 std::vector<int>::iterator it; std::sort (first,first+5); // 5 10 15 20 25 std::sort (second,second+5); // 10 20 30 40 50 it=std::set_union (first, first+5, second, second+5, v.begin()); v.resize(it-v.begin()); std::cout << "The union has " << (v.size()) << " elements:\n"; for (it=v.begin(); it!=v.end(); ++it) { std::cout << ' ' << *it; } std::cout << std::endl; } int main(int argc, char *argv[]) { std::cout << "SetDifference" << endl; ExampleSetDifference(); std::cout << "SetSymmetricDifference" << endl; ExampleSetSymmetricDifference(); std::cout << "SetUnion" << endl; ExampleSetUnion(); return 0; }
输出:
SetDifference The difference has 4 elements: 5 15 15 25 SetSymmetricDifference size 7 0 3 4 6 6 7 8 SetUnion The union has 9 elements: 5 10 15 15 20 25 30 40 50 [Finished in 0.3s]