80.遍历算法

常用遍历算法
    for_each  可有有返回值
    可以绑定参数进行输出
    transform  将容器中的数据进行搬运到另一个容器中
    注意:目标容器需要开辟空间
main.cpp

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;


/*
遍历算法 遍历容器元素
@param beg 开始迭代器
@param end 结束迭代器
@param _callback  函数回调或者函数对象
@return 函数对象
*/

//void myPrint(int v)
//{
//	cout << v << endl;
//}

struct myPrint01
{
	void operator()(int v)
	{
		cout << v << endl;
	}
};

void test01()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	for_each(v.begin(), v.end(), myPrint01());
}


struct myPrint02
{
	void operator()(int v)
	{
		cout << v << endl;
		m_Count++;
	}
	int m_Count;
};
//2 for_each有返回值
void test02()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	myPrint02 print2 = for_each(v.begin(), v.end(), myPrint02());//输出 0,1,2.。。。9
	cout << "print2.m_Count== " << print2.m_Count << endl;//print2.m_Count ==10
}

//3 for_each可以绑定参数进行输出
struct myPrint03 :public binary_function<int, int, void>
{
	void operator()(int v, int start) const
	{
		cout << v + start << endl;
	}
};

void test03()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}

	for_each(v.begin(), v.end(), bind2nd(myPrint03(), 10000));
	/*输出
	10000
	10001
	10002
	10003
	10004
	10005
	10006
	10007
	10008
	10009
	*/
}


/*
transform算法 将指定容器区间元素搬运到另一容器中
注意 : transform 不会给目标容器分配内存,所以需要我们提前分配好内存
@param beg1 源容器开始迭代器
@param end1 源容器结束迭代器
@param beg2 目标容器开始迭代器
@param _cakkback 回调函数或者函数对象
@return 返回目标容器迭代器
*/

class TransForm
{
public:
	int operator()(int val)
	{
		return val + 10;
	}
};
void test04()
{
	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(), [](int val){ cout << val << " "; });
	//输出:10 11 12 13 14 15 16 17 18 19
}

//transform 第二种用法 将两个容器数据相加搬运到目标容器
class TransForm2
{
public:
	int operator()(int val, int val2)
	{
		return val + val2;
	}
};

void test05()
{
	vector<int>v1;
	vector<int>v2;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(100 + i);
		v2.push_back(200 + i);
	}
	vector<int>vTarget; //目标容器
	vTarget.resize(v1.size());
	transform(v1.begin(), v1.end(), v2.begin(), vTarget.begin(), TransForm2());

	// 300 302...
	for_each(vTarget.begin(), vTarget.end(), [](int val){ cout << val << " "; });
	//输出:300 302 304 306 308 310 312 314 316 318

}

int main(){

	//test01();

	//test02();

	//test03();

	//test04();

	test05();
	system("pause");
	return EXIT_SUCCESS;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值