for_each用法

来源:互联网 发布:解封电脑机器码软件 编辑:程序博客网 时间:2024/06/05 17:51
template <class InputIterator, class Function>   Function for_each (InputIterator first, InputIterator last, Function f);
<algorithm>

Apply function to range

Applies function f to each of the elements in the range [first,last).

The behavior of this template function is equivalent to:

template<class InputIterator, class Function>  Function for_each(InputIterator first, InputIterator last, Function f)  {    while ( first!=last ) f(*first++);    return f;  }

#include<iostream>#include<algorithm>#include<vector>using namespace std;struct info{int key;int value;bool operator()(info A){cout<<A.key<<"\t"<<A.value<<endl;return 1;}};int main(){vector<info>vec(4);int i;for(i=0;i<4;i++){vec[i].key=i;vec[i].value=2*i;}for_each(vec.begin(),vec.end(),info());}


Parameters

first, last
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
f
Unary function taking an element in the range as argument. This can either be a pointer to a function or an object whose class overloads operator().
Its return value, if any, is ignored.

Return value

The same as f.
原创粉丝点击