95 常用 集合算法 set_intersection set_union set_difference

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值