天天看點

[C++STL]常用集合算法

[C++STL]常用集合算法
[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;
}

           

測試結果:

[C++STL]常用集合算法

總結:

[C++STL]常用集合算法
[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(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;
}

           

測試結果:

[C++STL]常用集合算法

總結:

[C++STL]常用集合算法
[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(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]常用集合算法

總結:

[C++STL]常用集合算法

繼續閱讀