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

一. 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 element
void 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 initialized
template <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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值