有求必应

导航

C++探究foreach算法

for_each在algorithm.h 中

template<class _InIt,
	class _Fn1> inline
	_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
	{	// perform function for each element
	_DEBUG_RANGE_PTR(_First, _Last, _Func);
	_For_each_unchecked(_Unchecked(_First), _Unchecked(_Last), _Func);
	return (_Func);
	}

  

_Func可以是一个普通函数,可以是一个函数对象。
返回值为函数对象,当需要返回值时,写一个函数对象作为回调函数入口地址。
#include <iostream>
#include<algorithm>
#include "functional"
#include <vector>
using namespace std;

class MyShow
{
public:
	void operator()(int n)
	{
		cout << n << " ";
		num++;
	}
	int num = 0;
};
void show(int &n)
{
	cout << n << " ";
}
void main()
{
	vector<int> v1;
	for (int i = 0; i < 5; i++)
	{
		v1.push_back(i + 2);
	}
	for_each(v1.begin(),v1.end(),show);
	cout << endl;
	MyShow t1;
	MyShow tmp = for_each(v1.begin(), v1.end(), t1);
	cout << endl;
	cout << "t1:" << t1.num << endl;
	cout <<"tmp:"<< tmp.num << endl;
	cout << "hello" << endl;
	system("pause");
}

  

探究for_each遍历类

#include <iostream>
#include<algorithm>
#include <functional>
#include <vector>
using namespace std;
class Ticket
{
public:
	Ticket()
	{
		;
	}
	int num;
	int id;
	char zimu;
};
class MyShow : public std::binary_function<Ticket*, char, bool>
{
public:
	bool operator()(const Ticket* t, const char &c) const
	{
		if (t->zimu == c)
		{
			cout << "车号:" << t->num << endl;
			cout << "座位:" << t->id<<"排"<<t->zimu<<"座" << endl;
			return true;
		}
		return false;
	}
};
void main()
{
	vector<Ticket*> v1;
	for (int num = 0; num < 2; num++)
	{
		for (int id = 0; id < 5; id++)
		{
			for (int i = 0; i < 5; i++)
			{
				Ticket *tmp = new Ticket;
				tmp->num = num;
				tmp->id = id;
				tmp->zimu = 'A' + i;
				v1.push_back(tmp);
			}
		}
	}
	for_each(v1.begin(),v1.end(), bind2nd(MyShow(),'A'));
	for (vector<Ticket*>::iterator it = v1.begin(); it != v1.end(); )
	{
		delete (*it);
		it = v1.erase(it);
		it++;
	}
	cout  << endl;
	cout << "hello" << endl;
	system("pause");
}

 

  

 

posted on 2018-10-03 17:25  名侦探江户川  阅读(3030)  评论(0编辑  收藏  举报