C++ //常用集合算法 //set_intersection //求俩个容器的交集 //set_union //求两个容器的并集 //set_difference //求两个容器的差集
1 //常用集合算法 2 //set_intersection //求俩个容器的交集 3 //set_union //求两个容器的并集 4 //set_difference //求两个容器的差集 5 6 #include<iostream> 7 #include<vector> 8 #include<algorithm> 9 using namespace std; 10 11 12 void myprint(int v) 13 { 14 cout << v << " "; 15 } 16 //set_intersection //求俩个容器的交集 (必须是有序序列) 17 void test01() 18 { 19 vector<int>v1; 20 vector<int>v2; 21 22 23 for (int i = 0; i < 10; i++) 24 { 25 v1.push_back(i); //0 -9 26 v2.push_back(i + 5); //5-14 27 } 28 29 vector<int>vTarget; 30 //目标容器需要提前开辟空间. 31 //最特殊的情况 大容器包含小容器 开辟空间 取小容器的size 32 vTarget.resize(min(v1.size(), v2.size())); 33 34 //获取交际 35 vector<int>::iterator itEnd=set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); 36 37 for_each(vTarget.begin(), itEnd, myprint); 38 cout << endl; 39 40 } 41 42 //set_union 并集 有序序列 43 44 class MyPrint 45 { 46 public: 47 48 void operator()(int l) 49 { 50 cout << l << " "; 51 } 52 }; 53 54 55 void test02() 56 { 57 vector<int>v1; 58 vector<int>v2; 59 60 for (int i = 0; i < 10; i++) 61 { 62 v1.push_back(i); 63 v2.push_back(i + 5); 64 } 65 66 vector<int>vTarget; 67 //最特殊的情况是 没有交集 并集两个容器相加 68 vTarget.resize(v1.size()+v2.size()); 69 70 vector<int>::iterator itEnd=set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); 71 for_each(vTarget.begin(), itEnd, MyPrint()); 72 cout << endl; 73 74 } 75 76 //set_difference //求两个容器的差集 77 void myPrint(int vc) 78 { 79 cout << vc << " "; 80 } 81 void test03() 82 { 83 vector<int>v1; 84 vector<int>v2; 85 86 for (int i = 0; i < 10; i++) 87 { 88 v1.push_back(i); 89 v2.push_back(i + 5); 90 } 91 92 //差集放到目标容器中 93 //最特殊的情况 两个容器没有交集 取大的空间 94 vector<int>vTarget; 95 vTarget.resize(max(v1.size(), v2.size())); 96 97 cout << "V1和V2的差集" << endl; 98 vector<int>::iterator Itend = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); 99 100 101 for_each(vTarget.begin(), Itend, myPrint); 102 cout << endl; 103 104 cout << "V2和V1的差集" << endl; 105 Itend = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget.begin()); 106 107 for_each(vTarget.begin(), Itend, myPrint); 108 cout << endl; 109 110 } 111 112 int main() 113 { 114 test01(); 115 116 test02(); 117 118 test03(); 119 system("pause"); 120 return 0; 121 }
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15158704.html