#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//stl常见算法
/*
1.algorithm
2.numeric
3.functional
*/
void mprint(int val)
{
cout << val << " ";
}
//常用 集合算法 set_intersection set_union set_difference
//内置数据类型
//交集 set_intersection
void test01()
{
vector<int>v1,v2;
for (int i = 1; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i+5);
}
for_each(v1.begin(), v1.end(), mprint);//1 2 3 4 5 6 7 8 9
cout << endl;
for_each(v2.begin(), v2.end(), mprint);//6 7 8 9 10 11 12 13 14
cout << endl;
vector<int>vTarget;
vTarget.resize(min(v1.size(), v2.size()));
vector<int>::iterator endit = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin()); //endit 终止的 迭代器。 vTarget 的size 一般会大于 endit
for_each(vTarget.begin(), endit, mprint);//6 7 8 9
cout << endl;
}
//set_union 并集
void test02()
{
vector<int>v1, v2;
for (int i = 1; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
for_each(v1.begin(), v1.end(), mprint);//1 2 3 4 5 6 7 8 9
cout << endl;
for_each(v2.begin(), v2.end(), mprint);//6 7 8 9 10 11 12 13 14
cout << endl;
vector<int>vTarget;
vTarget.resize(v1.size()+v2.size());
vector<int>::iterator endit = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), endit, mprint);//1 2 3 4 5 6 7 8 9 10 11 12 13 14
cout << endl;
}
//set_difference 差集
void test03()
{
vector<int>v1, v2;
for (int i = 1; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
for_each(v1.begin(), v1.end(), mprint);//1 2 3 4 5 6 7 8 9
cout << endl;
for_each(v2.begin(), v2.end(), mprint);//6 7 8 9 10 11 12 13 14
cout << endl;
// 求v1和v2 的差集, 在v1中,不存在v2 中
vector<int>vTarget;
vTarget.resize(max(v1.size(),v2.size()));
vector<int>::iterator endit = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), endit, mprint);//1 2 3 4 5
cout << endl;
// 求v2和v1 的差集, 在v2中,不存在v1 中
vector<int>vTarget1;
vTarget1.resize(max(v1.size(), v2.size()));
endit = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), vTarget1.begin()); // 求v1和v2 的差集, 在v1中,不存在v2 中
for_each(vTarget1.begin(), endit, mprint);//10 11 12 13 14
cout << endl;
}
int main()
{
test01();
cout << "+++++++++++++++++++++" << endl;
test02();
cout << "+++++++++++++++++++++" << endl;
test03();
system("pause");
return 0;
}
95 常用 集合算法 set_intersection set_union set_difference
最新推荐文章于 2024-10-01 23:05:47 发布