01 常用遍历算法for_each

02 常用的遍历算法transform


01 常用遍历算法for_each

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>

void mycompare(int val)
{
	cout << val << " ";
}

class Mycompare {
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	for_each(v.begin(), v.end(), mycompare);
	cout << endl;
	for_each(v.begin(), v.end(), Mycompare());
	cout << endl;
}
int main()
{
	test01();

	system("pause");
	return 0;
}

02 常用的遍历算法transform

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>

void myprint(int val)
{
	cout << val << " ";
}

class Transform
{
public:
	int operator()(int val)
	{
		return val+1000;
	}
};

void test01()
{
	vector<int> v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	vector<int> vtarget;//目标容器
	vtarget.resize(v.size()); //目标容器,需要提前开辟空间,否则塞不进去

	transform(v.begin(), v.end(), vtarget.begin(), Transform());
	for_each(vtarget.begin(), vtarget.end(), myprint);
	cout << endl;
	
}
int main()
{
	test01();

	system("pause");
	return 0;
}