zoukankan      html  css  js  c++  java
  • 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");
    }

      

  • 相关阅读:
    Python 3学习 ——目录 Json Pickle
    Python 3 学习——函数扩展and迭代器生成器装饰器
    Python 3 学习——深浅拷贝以及函数
    Python 3 学习的第七小节——Linux-Ubuntu
    Python 3 —— 文件操作
    Python 3 学习的第五小节——字符编码与三级菜单实践
    关于PHP代码复用‘traits’的一段代码
    一个将对象彻底冻结的函数
    详解vue-cli脚手架项目-package.json
    关于element-ui日期选择器disabledDate使用心得
  • 原文地址:https://www.cnblogs.com/smh2015/p/9740246.html
Copyright © 2011-2022 走看看