C++进阶STL-常用的遍历算法

for_each


#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class Person
{
public:
	Person(int age, int id) :m_age(age), m_id(id)
	{
	}

	int m_age;
	int m_id;
};

struct Print
{
	void operator()(const Person& p)
	{
		cout << "age: " << p.m_age << " " << "id: " << p.m_id << endl;
	}
};
int main()
{

	vector<Person> v1;
	Person p1(1, 1), p2(2, 2), p3(3, 3), p4(4, 4), p5(5, 5);


	v1.push_back(p4);
	v1.push_back(p5);
	v1.push_back(p1);
	v1.push_back(p2);
	v1.push_back(p3);
	v1.push_back(p4);
	v1.push_back(p4);
	v1.push_back(p5);

	for_each(v1.begin(), v1.end(), Print());

    return 0;
}

结果:在这里插入图片描述



transform:将一个(或者两个)容器进行操作复制给另一个容器

在这里插入图片描述

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;

class Person
{
public:
	Person(int age, int id) :m_age(age), m_id(id)
	{
	}
	Person()
	{

	}
	int m_age;
	int m_id;
};

struct Print
{
	void operator()(const Person& p)
	{
		cout << "age: " << p.m_age << " " << "id: " << p.m_id << endl;
	}
};

struct op_Increse
{
	Person operator()( Person& p)
	{
		p.m_age += 1;
		p.m_id += 1;
		return p;
	}
};

struct op_Increse_2
{
	Person operator()(Person& p1, Person& p2)
	{
		p1.m_age += p2.m_age;
		p1.m_id += p2.m_id;
		return p1;
	}
};

int main()
{

	vector<Person> v1;
	Person p1(1, 1), p2(2, 2), p3(3, 3), p4(4, 4), p5(5, 5);


	v1.push_back(p4);
	v1.push_back(p5);
	v1.push_back(p1);
	v1.push_back(p2);
	v1.push_back(p3);
	v1.push_back(p4);
	v1.push_back(p4);
	v1.push_back(p5);

	vector<Person> v2;
	v2.resize(v1.size());
	
	//在第一次调用transform之后,v1每个值也加1,因为op_Increase()函数给的是v1的引用
	transform(v1.begin(), v1.end(), v2.begin(), op_Increse()); //v1+1=v2,v1作为回调函数的参数,v2作为返回结果
	for_each(v2.begin(), v2.end(), Print());

	cout << "---------------------------" << endl;

	transform(v1.begin(), v1.end(), v1.begin(), v2.begin(), op_Increse_2());//v2=v1+v2,v1,v2 都作为回调函数的参数,结果再给v2
	for_each(v2.begin(), v2.end(), Print());

    return 0;
}


结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zzyczzyc/article/details/83016093