C++的STL算法for_each

来源:互联网 发布:通过网络走群众路线 编辑:程序博客网 时间:2024/05/17 08:32

for_each()函数将调用者提供的操作施加于每一个元素身上。它既可以是非变动性算法,也可以说是变动性算法。

[cpp] view plain copy
 print?
  1. template <class InputIterator, class Function>  
  2.    Function for_each (InputIterator first, InputIterator last, Function f);  

将函数f施加于区间[first,last)的每一个元素身上。其实现:

[cpp] view plain copy
 print?
  1. template<class InputIterator, class Function>  
  2.   Function for_each(InputIterator first, InputIterator last, Function f)  
  3.   {  
  4.     for ( ; first!=last; ++first ) f(*first);  
  5.     return f;  
  6.   }  
它返回f已在算法内部变动过的一个副本。
f可以是普通函数,也可是仿函数。它的任何返回值都将被忽略。


第三个参数在调用的时候可以是普通函数名;也可以说是函数对象,(定义重载operator的类)

程序实例:

下面的例子实现了两个功能:

一是使用普通函数print()打印所以元素;而是使用自定义的仿函数,即函数对象,来改变每个元素:将每个元素乘以3.

main.cpp:

[cpp] view plain copy
 print?
  1. #include "algostuff.h"  
  2.   
  3. using namespace std;  
  4.   
  5. void print(int elem)  
  6. {  
  7.     cout << elem << " ";  
  8. }  
  9.   
  10. //define a functor  
  11. //multiply every element with the value initialized  
  12. template <class T>  
  13. class MultiplyValue{  
  14. private:  
  15.     T value;  
  16. public:  
  17.     MultiplyValue(const T val):value(val){}  
  18.   
  19.     //the function call  
  20.     void operator()(T &elem)  
  21.     {  
  22.         elem *= value;  
  23.     }  
  24. };  
  25.   
  26. int main()  
  27. {  
  28.     vector<int> intVec;  
  29.     INSERT_ELEMENTS(intVec,1,9);  
  30.   
  31.     cout << "elements : " << endl;  
  32.     for_each(intVec.begin(),intVec.end(),print);  
  33.     cout << endl << endl;  
  34.   
  35.     for_each(intVec.begin(),intVec.end(),MultiplyValue<int>(3));  
  36.     PRINT_ELEMNTS(intVec,"after multiply : ");  
  37.     cout << endl;  
  38. }  
algostuff.h:
[cpp] view plain copy
 print?
  1. #ifndef ALGOSTUFF_H  
  2. #define ALGOSTUFF_H  
  3.   
  4. #include <iostream>  
  5. #include <vector>  
  6. #include <list>  
  7. #include <deque>  
  8. #include <set>  
  9. #include <map>  
  10. #include <string>  
  11. #include <algorithm>  
  12. #include <functional>  
  13. #include <numeric>  
  14.   
  15. //print all the elements  
  16. template <class T>  
  17. inline void PRINT_ELEMNTS(const T &col,const char *optcstr = " ")  
  18. {  
  19.     typename T::const_iterator pos;  
  20.     cout << optcstr;  
  21.     for(pos = col.begin();pos != col.end();++pos)  
  22.         cout << *pos << " ";  
  23.     cout << endl;  
  24. }  
  25.   
  26. //insert values from first to last into the collection  
  27. template <class T>  
  28. inline void INSERT_ELEMENTS(T &col,int first,int last)  
  29. {  
  30.     for(int i = first;i <= last;++i)  
  31.         col.insert(col.end(),i);  
  32. }  
  33.   
  34. #endif  
运行结果:
0 0
原创粉丝点击