C++值常用集合算法
set_intersection
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include<algorithm>
class MyPrint
{
public:
void operator()(int val)
{
cout << val<<" ";
}
};
void test()
{
vector<int> v;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
v2.push_back(i + 3);
}
vector<int>Target;
//目标容器需要开辟空间
//最特殊的情况 大容器包含小容器 取小容器大小即可
Target.resize(min(v.size(), v2.size()));
//获取交集
vector<int>::iterator itEnd = set_intersection(v.begin(), v.end(), v2.begin(), v2.end(), Target.begin());
for_each(Target.begin(), itEnd, MyPrint());
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
set_union
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include<algorithm>
class MyPrint
{
public:
void operator()(int val)
{
cout << val<<" ";
}
};
void test()
{
vector<int> v;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
v2.push_back(i + 3);
}
vector<int>Target;
//目标容器需要开辟空间
//最特殊的情况 两个容器没有交集 目标容器的大小就是二个容器相加
Target.resize(v.size() + v2.size());
//获取交集
vector<int>::iterator itEnd = set_union(v.begin(), v.end(), v2.begin(), v2.end(), Target.begin());
for_each(Target.begin(), itEnd, MyPrint());
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
set_difference
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include<algorithm>
class MyPrint
{
public:
void operator()(int val)
{
cout << val<<" ";
}
};
void test()
{
vector<int> v;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
v2.push_back(i + 3);
}
vector<int>Target;
//目标容器需要开辟空间
//最特殊的情况 两个容器没有交集 取大的容器
Target.resize(max(v.size() ,v2.size()));
//获取交集
cout << "v和v2的差集" << endl;
vector<int>::iterator itEnd = set_difference(v.begin(), v.end(), v2.begin(), v2.end(), Target.begin());
for_each(Target.begin(), itEnd, MyPrint());
cout << endl;
cout << "v2和v1的差集" << endl;
itEnd = set_difference(v2.begin(), v2.end(), v.begin(), v.end(), Target.begin());
for_each(Target.begin(), itEnd, MyPrint());
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}