[C++STL]常用集合算法
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[C++STL]常用集合算法相关的知识,希望对你有一定的参考价值。
代码如下:
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
class myPrint
{
public:
void operator()(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);
}
for_each(v1.begin(), v1.end(), myPrint());
cout << endl;
for_each(v2.begin(), v2.end(), myPrint());
cout << endl;
vector<int >v3;
v3.resize(min(v1.size(),v2.size()));
vector<int>::iterator itEnd = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
for_each(v3.begin(), itEnd, myPrint());
cout << endl;
}
int main()
{
test01();
return 0;
}
测试结果:
总结:
代码如下:
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
class myPrint
{
public:
void operator()(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);
}
for_each(v1.begin(), v1.end(), myPrint());
cout << endl;
for_each(v2.begin(), v2.end(), myPrint());
cout << endl;
vector<int >v3;
v3.resize(v1.size() + v2.size());
vector<int>::iterator itEnd = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
for_each(v3.begin(), itEnd, myPrint());
cout << endl;
}
int main()
{
test01();
return 0;
}
测试结果:
总结:
代码如下:
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
class myPrint
{
public:
void operator()(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);
}
for_each(v1.begin(), v1.end(), myPrint());
cout << endl;
for_each(v2.begin(), v2.end(), myPrint());
cout << endl;
vector<int >v3;
v3.resize(max(v1.size() , v2.size()));
//v1和v2的差集
vector<int>::iterator itEnd = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
for_each(v3.begin(), itEnd, myPrint());
cout << endl;
cout << "---------------------------------------" << endl;
//v2和v1的差集
vector<int>::iterator itEnd02 = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), v3.begin());
for_each(v3.begin(), itEnd02, myPrint());
cout << endl;
}
int main()
{
test01();
return 0;
}
测试结果:
总结:
以上是关于[C++STL]常用集合算法的主要内容,如果未能解决你的问题,请参考以下文章