set_intersection:求兩個容器的交集
set_union:求兩個集合的並集
set_difference:求兩個集合的差集
1.set_intersection
#include<iostream> using namespace std; #include <vector> #include <algorithm> //常用集合算法 set_intersection void myPrint(int val) { cout << val << " "; } void test01() { vector<int>v1; vector<int>v2; for (int i = 0; i < 10; i++) { v1.push_back(i); // 0 ~ 9 v2.push_back(i + 5); // 5 ~ 14 } vector<int>vTarget; //目標容器需要提前開辟空間 //最特殊情況 大容器包含小容器 開辟空間 取小容器的size即可 vTarget.resize(min(v1.size(), v2.size())); //獲取交集 vector<int>::iterator itEnd = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); for_each(vTarget.begin(), itEnd, myPrint); cout << endl; } int main() { test01(); system("pause"); return 0; }
2.set_union
#include<iostream> using namespace std; #include <vector> #include <algorithm> //常用集合算法 set_union void myPrint(int val) { cout << val << " "; } void test01() { vector<int>v1; vector<int>v2; for (int i = 0; i < 10; i++) { v1.push_back(i); v2.push_back(i + 5); } vector<int>vTarget; //目標容器提前開辟空間 //最特殊情況 兩個容器沒有交集,並集就是兩個容器size相加 vTarget.resize(v1.size() + v2.size()); vector<int>::iterator itEnd = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); for_each(vTarget.begin(), itEnd, myPrint); cout << endl; } int main() { test01(); system("pause"); return 0; }
3.set_difference
#include<iostream> using namespace std; #include <vector> #include <algorithm> void myPrint(int val) { cout << val << " "; } //常用集合算法 set_difference void test01() { vector<int>v1; vector<int>v2; for (int i = 0; i < 10; i++) { v1.push_back(i); v2.push_back(i+5); } //創建目標容器 vector<int>vTarget; //給目標容器開辟空間 //最特殊情況 兩個容器沒有交集 取兩個容器中大的size作為目標容器開辟空間 vTarget.resize( max(v1.size(),v2.size()) ); cout << "v1和v2的差集為:" << endl; vector<int>::iterator itEnd = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); for_each(vTarget.begin(), itEnd, myPrint); cout << endl; cout << "v2和v1的差集為:" << endl; itEnd = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget.begin()); for_each(vTarget.begin(), itEnd, myPrint); cout << endl; } int main() { test01(); system("pause"); return 0; }