zoukankan      html  css  js  c++  java
  • for_each算法

    算法详解

    for_each( )算法非常的灵活,它可以不用的方式存取,处理,修改每一个元素。

    接口
    Function for_each(InputIterator _First, InputIterator _Last, Function _Func)
    参数
    _First, 指定容器的起始位置
    _Last ,指定容器的最后一个元素的下一个位置
    _Func 用户自行定义的函数或者仿函数,_Func会作用于容器内的每个元素

    返回值
    返回_Func 的一个副本,一般该返回值都会被忽略

    复杂度
    线性

    算法实现
    template<class InputIterator, class Function>
    Function for_each(InputIterator _First, InputIterator _Last, Function _Func)
    {
    	while (_First != _Last)
    	{
    		_Func(*_First);	//call _Func() for actual element
    		_First++;
    	}
    
    	return (_Func);
    }

    应用

    #include "stdafx.h"
    #include <string.h>
    #include <algorithm>
    #include <vector>
    #include <deque>
    #include <functional>
    #include <iostream>
    #include <list>
    #include <sstream>
    #include <iterator>
    #include <functional>
    #include <stdlib.h>
    #define  MAX_NUM 10
    
    //#include "print.h"
    using namespace std;
    
    //function called for each element
    void Print(int elem)
    {
    	cout << elem << ' ';
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	vector<int> vecCollection;
    	for (int i = 0; i < MAX_NUM; ++i)
    	{
    		vecCollection.push_back(i);
    	}
    	
    	//call Print() for each element
    	for_each(vecCollection.begin(), vecCollection.end(), Print);
    
    	cout << endl;
    }

    输出
  • 相关阅读:
    Numpy
    啊大大阿达
    asda
    啊大大
    初识python
    初识python
    初识python
    初识python
    初识python
    初识python
  • 原文地址:https://www.cnblogs.com/jinxiang1224/p/8468429.html
Copyright © 2011-2022 走看看