c++ 标准模板库 STL 算法之 for_each 函数的使用用法详解
来源:互联网 发布:上虞司法淘宝拍卖 编辑:程序博客网 时间:2024/05/12 12:09
template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function fn);
[first,last)
.The behavior of this template function is equivalent to:
123456789
template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function fn){ while (first!=last) { fn (*first); ++first; } return fn; // or, since C++11: return move(fn);}
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 andlast, including the element pointed by first but not the element pointed bylast. - fn
- Unary function that accepts an element in the range as argument.
This can either be a function pointer or a move constructible function object.Its return value, if any, is ignored.
Applies a specified function object to each element in a forward order within a range and returns the function object.
template<class InputIterator, class Function> Function for_each( InputIterator _First, InputIterator _Last, Function _Func );
ParametersReturn ValueA copy of the function object after it has been applied to all of the elements in the range.
RemarksThe algorithm for_each is very flexible, allowing the modification of each element within a range in different, user-specified ways. Templatized functions may be reused in a modified form by passing different parameters. User-defined functions may accumulate information within an internal state that the algorithm may return after processing all of the elements in the range.
The range referenced must be valid; all pointers must be dereferenceable and, within the sequence, the last position must be reachable from the first by incrementation.
The complexity is linear with at most (_Last – _First) comparisons.
头文件:
<algorithm>
说明:
for_each算法范围 [_First, _ Last) 中的每个元素调用函数_Fn1,并返回输入的参数 _Func。此函数不会修改序列中的任何元素。
// for_each example#include <iostream> // std::cout#include <algorithm> // std::for_each#include <vector> // std::vector#include <list>void myfunction (int i){ // function: std::cout << ' ' << i;}struct myclass{ // function object type: void operator() (int i) {std::cout << ' ' << i;}} myobject;void test_my(){ std::vector<int> myvector; myvector.push_back(10); myvector.push_back(20); myvector.push_back(30); std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myfunction); std::cout << '\n'; // or: std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myobject); std::cout << '\n'; std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myclass()); std::cout << '\n';}/******运行结果:myvector contains: 10 20 30myvector contains: 10 20 30myvector contains: 10 20 30******///print为仿函数struct print{ int count; print(){count = 0;} void operator()(int x) { std::cout << x << std::endl; ++count; }};void test_print(){ using namespace std; list<int> testlist; //初始化 for ( size_t i = 1991; i <2013 ; ++i) { testlist.push_back(i); } //遍历testlist元素并打印 print p = for_each(testlist.begin(), testlist.end(), print()); //打印testlist元素个数 cout << "元素个数是:"<<p.count << endl;}/******运行结果:1991199219931994199519961997199819992000200120022003200420052006200720082009201020112012元素个数是:22******/class Multi_By_x{ private: int multiplier; public: Multi_By_x(const int& k) : multiplier(k) { } void operator()(const int& x) { std::cout << x * multiplier << " " << std::endl; }};void test_Multi_By_x(){ int sequence[6] = {2007,2010,2011,2012,2013,2014}; using std::vector; vector<int> v(sequence, sequence+6); Multi_By_x Multi2(2); for_each(v.begin(),v.end(),Multi2); // Apply function}/*************运行结果:401440204022402440264028*************/int main (){ test_my(); std::cout<<"\n***************************************************\n"; test_print(); std::cout<<"\n***************************************************\n"; test_Multi_By_x(); std::cout<<"\n***************************************************\n"; return 0;}/***************myvector contains: 10 20 30myvector contains: 10 20 30myvector contains: 10 20 30***************************************************1991199219931994199519961997199819992000200120022003200420052006200720082009201020112012元素个数是:22***************************************************401440204022402440264028***************************************************Process returned 0 (0x0) execution time : 0.039 sPress any key to continue.****************/
再看一下MSDN上边给出的例子程序:
#include <vector>#include <algorithm>#include <iostream>// The function object multiplies an element by a Factortemplate <class Type>class MultValue{private: Type Factor; // The value to multiply bypublic: // Constructor initializes the value to multiply by MultValue ( const Type& _Val ) : Factor ( _Val ) { } // The function call for the element to be multiplied void operator ( ) ( Type& elem ) const { elem *= Factor; }};// The function object to determine the averageclass Average{private: long num; // The number of elements long sum; // The sum of the elementspublic: // Constructor initializes the value to multiply by Average ( ) : num ( 0 ) , sum ( 0 ) { } // The function call to process the next elment void operator ( ) ( int elem ) { num++; // Increment the element count sum += elem; // Add the value to the partial sum } // return Average operator double ( ) { return static_cast <double> (sum)/static_cast <double> (num); }};int main( ){ using namespace std; vector <int> v1; vector <int>::iterator Iter1; // Constructing vector v1 int i; for ( i = -4 ; i <= 2 ; i++ ) { v1.push_back( i ); } cout << "Original vector v1 = ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; // Using for_each to multiply each element by a Factor for_each ( v1.begin ( ) , v1.end ( ) , MultValue<int> ( -2 ) ); cout << "Multiplying the elements of the vector v1\n " << "by the factor -2 gives:\n v1mod1 = ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; // The function object is templatized and so can be // used again on the elements with a different Factor for_each (v1.begin ( ) , v1.end ( ) , MultValue<int> (5 ) ); cout << "Multiplying the elements of the vector v1mod\n " << "by the factor 5 gives:\n v1mod2 = ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; // The local state of a function object can accumulate // information about a sequence of actions that the // return value can make available, here the Average double avemod2 = for_each ( v1.begin ( ) , v1.end ( ) ,Average ( ) ); cout << "The average of the elements of v1 is:\n Average ( v1mod2 ) = " << avemod2 << "." << endl;}/*****************运行结果如下:Original vector v1 = ( -4 -3 -2 -1 0 1 2 ).Multiplying the elements of the vector v1 by the factor -2 gives: v1mod1 = ( 8 6 4 2 0 -2 -4 ).Multiplying the elements of the vector v1mod by the factor 5 gives: v1mod2 = ( 40 30 20 10 0 -10 -20 ).The average of the elements of v1 is: Average ( v1mod2 ) = 10.Process returned 0 (0x0) execution time : 0.122 sPress any key to continue.******************/
- c++ 标准模板库 STL 算法之 for_each 函数的使用用法详解
- STL算法之for_each
- STL学习之for_each的用法
- STL之sort和for_each的用法
- STL 标准模板库之<set>详解
- 标准模板库STL详解之vector
- 使用标准模板库 (STL)之二
- STL for_each 和函数对象(function object) 使用详解
- STL for_each 和函数对象(function object) 使用详解
- C++的STL算法for_each
- STL标准模板库 list的使用
- C++:标准模板库(STL)
- C++STL标准模板库
- 标准模板库(五):STL算法函数介绍
- 标准模板库(六):STL算法函数介绍
- 标准模板库(八):STL算法函数介绍
- for_each()算法的使用
- 标准模板库(四):STL的算法中的函数介绍
- 循环队列
- nginx的301
- PHP 文件操作
- 栈
- 二次贝塞尔曲线应用-生成飞机路径示意图
- c++ 标准模板库 STL 算法之 for_each 函数的使用用法详解
- Add Binary
- 栈应用之一数制转换
- android数据存储_SharedPreferences的简单使用
- Domino - NOTES.INI file
- nagios 配置与添加小太阳图标
- Android APP应用的背景
- 网络爬虫
- HDU 3864 pollard_rho大数质因子分解