STL学习笔记----9.STL算法之 for_each()

来源:互联网 发布:c语言百分制转换 编辑:程序博客网 时间:2024/05/16 09:08

一. for_each()算法

for_each (InputIterator beg, InputIterator end, UnaryProc op)
1. 对区间[beg, end)中的每个元素elem调用,op(elem)

2. op的任何返回值都会被忽略

3. for_each()返回op仿函数的一个副本。

4. 调用op的次数为[beg, end)的个数次。

二. for_each()例子

1. 一般函数作为for_each()的参数

#include "algostuff.hpp"using namespace std;// function called for each elementvoid print (int elem){    cout << elem << ' ';}int main(){        vector<int> coll;        INSERT_ELEMENTS(coll,1,9);        // for_each 对每个 elem 将调用 print(elem)        for_each (coll.begin(), coll.end(),  // range                  print);                    // operation        cout << endl;}

2. 仿函数作为for_each()的参数

#include "algostuff.hpp"using namespace std;// function object that adds the value with which it is initializedtemplate <c1ass T>c1ass AddValue {      private:        T theValue;    // value to add      public:        // 构造函数,初始化theValue        AddValue (const T& v) : theValue(v) {        }        // the function call for the element adds the value        void operator() (T& elem) const {  //不好理解?看成 void Fun(int& elem) const {},好理解了吧!!            elem += theValue;        }};int main(){        vector<int> coll;        INSERT_ELEMENTS(coll,1,9);        // 每个 element 加 10        for_each (coll.begin(), coll.end(),  // range                  AddValue<int>(10));        // 这个怎么理解????        //首先 AddValue(10)是一个构造函数,构造完后theValue=10,然后再调用operator(elem)!!        PRINT_ELEMENTS(coll);        // 每个 element 加 第一个值        for_each (coll.begin(), coll.end(),         // range                  AddValue<int>(*coll.begin()));    // operation        PRINT_ELEMENTS(coll);}
3. 利用for_each()的返回值
#include "algostuff.hpp"using namespace std;//仿函数,用来处理平均值c1ass MeanValue {      private:        long num;     // number of elements        long sum;     // sum of all element values      public:        // 构造函数        MeanValue () : num(0), sum(0) {        }        // 调用        // - process one more element of the sequence        void operator() (int elem) {            num++;         // increment count            sum += elem;   // add value        }        // 重载double类型运算符,没什么道理,只是返回平均值        operator double() {            return static_cast<double>(sum) / static_cast<double>(num);        }};int main(){        vector<int> coll;        INSERT_ELEMENTS(coll,1,8);        // 返回应该是仿函数,但是被转换成了double,这个是隐式转换        double mv = for_each (coll.begin(), coll.end(),  // range                              MeanValue());              // operation        cout << "mean value: " << mv << endl;}