• 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");
    }

      

  • 相关阅读:
    OpenCV 2.4.9
    开机黑屏 仅仅显示鼠标 电脑黑屏 仅仅有鼠标 移动 [已成功解决]
    吐槽一下CSDN的封停审查机制
    【课程分享】Oracle数据库系统project师
    Html的空格显示
    iOS UIWebView 访问https 绕过证书验证的方法
    Java实现 蓝桥杯VIP 算法训练 整除问题
    Java实现 蓝桥杯VIP 算法训练 数位分离
    Java实现 蓝桥杯VIP 算法训练 薪水计算
    Java实现 蓝桥杯VIP 算法训练 完数
  • 原文地址:https://www.cnblogs.com/smh2015/p/9740246.html
Copyright © 2020-2023  润新知