std::for_each() -<algorithm.h>
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
函数功能范围:
应用函数f指向[first, lst)的每一个元素。
模板函数的作用等效于:
template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f) { for ( ; first!=last; ++first ) f(*first); return f; }
参数:
first, last
输入迭代器指向一个序列的初始和最后位置。使用范围是容器[first, last)内的每一个元素,包括第一个元素但是不 包括最后一个。
f
该函数调用[first, last)内的一个元素作为参数,指向一个函数或者一个对象的重载操作符()(operator())。此 函数不修改序列内的所有元素。
返回值:
返回f
例子:
// for_each example #include <iostream> #include <algorithm> #include <vector> using namespace std; void myfunction (int i) { cout << " " << i; } struct myclass { void operator() (int i) {cout << " " << i;} } myobject; int main () { vector<int> myvector; myvector.push_back(10); myvector.push_back(20); myvector.push_back(30); cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myfunction); // or: cout << "\nmyvector contains:"; for_each (myvector.begin(), myvector.end(), myobject); cout << endl; return 0; }
输出:
myvector contains: 10 20 30
myvector contains: 10 20 30
更多高级用法请关注(algorithm—for_each() (2)) |