C++:STL-常用遍历算法

C++:STL-常用遍历算法_第1张图片

#include
#include
#include
#include

using namespace std;

//常用遍历算法for_each
//普通函数
void print(int val)
{
	cout << val << " ";
}
//仿函数
class print2
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
void test01()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(30);
	v.push_back(20);
	v.push_back(50);
	v.push_back(40);

	//遍历for_each(迭代器,迭代器,函数对象)
	for_each(v.begin(), v.end(), print);
	for_each(v.begin(), v.end(), print2());
	cout << endl;
}

//搬运容器到另一个容器中transform
//仿函数
class Transform
{
public:
	int operator()(int val)
	{
		return val;
	}
};
void test02()
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}

	vector<int>v2;
	//目标容器需要提前开辟空间
	v2.resize(v1.size());

	transform(v1.begin(), v1.end(),v2.begin(),Transform());
	for_each(v2.begin(), v2.end(), print);
	cout << endl;

}

int main()
{
	test02();

	system("pause");
	return 0;
}

你可能感兴趣的:(笔记)