STL-Algorithm: for_each

for_each(iterator,iterator,callback);

The first two parameter lists are iterators to traverse the container, and the third parameter is the corresponding callback function

The principle of the callback function is to pass parameters to the corresponding function body, and then operate

# include<iostream>
# include<algorithm>
# include<vector> 

using namespace std;

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

/*
基本数据类型 
遍历算法
*/
void test1()
{
	vector<int> v;
	
	v.push_back(1);
	v.push_back(5);
	v.push_back(4);
	v.push_back(2);
	v.push_back(6);
	
	for_each(v.begin(),v.end(),Print);
 } 

/*
自定义数据类型
for_each遍历 
*/ 
class Person{
	public:
		Person(int a,int b):index(a),age(b){}
	public:
		int age;
		int index;
};

void Print2(Person &p)
{
	cout << "index:" << p.index << " " << "age:" << p.age << endl;
}

void test2()
{
	vector<Person> vp;
	Person p1(1,4),p2(2,5),p3(3,6);
	vp.push_back(p1);
	vp.push_back(p2);
	vp.push_back(p3);
	
	for_each(vp.begin(),vp.end(),Print2); 
}

int main()
{
	//test1();
	test2();

 return 0;
}

operation result:

test1:

test2:

Guess you like

Origin blog.csdn.net/qq_40479037/article/details/87288932