码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 11 - STL - 函数对象(Function Object) (中)

时间:2015-09-25 12:41:57      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

我们再来看一个复杂的例子

需求:

我们需要对集合内每个元素加上一个特定的值

代码如下:

AddInt.h

class AddInt
{
private:
    int theValue;    // the value to add
public:
    // constructor initializes the value to add
    AddInt(int v) : theValue(v) { }

    // the "function call" for the element adds the value
    void operator() (int& elem) const 
    {
        elem += theValue;
    }
};

 

设置一个打印模板类

print.hpp

template <typename T>
inline void PRINT_ELEMENTS (const T& coll,
                            const std::string& optstr="")
{
    std::cout << optstr;
    for (const auto&  elem : coll) {
        std::cout << elem <<  ;
    }
    std::cout << std::endl;
}

 

测试程序:

list<int> coll;

// insert elements from 1 to 9
for (int i = 1; i <= 9; ++i) {
    coll.push_back(i);
}

PRINT_ELEMENTS(coll, "initialized:                ");

// add value 10 to each element
for_each(coll.begin(), coll.end(),    // range
    AddInt(10));               // operation

PRINT_ELEMENTS(coll, "after adding 10:            ");

// add value of first element to each element
for_each(coll.begin(), coll.end(),    // range
    AddInt(*coll.begin()));    // operation

PRINT_ELEMENTS(coll, "after adding first element: ");    

 

运行结果:

---------------- addFuncObject(): Run Start ----------------
initialized:                1 2 3 4 5 6 7 8 9
after adding 10:            11 12 13 14 15 16 17 18 19
after adding first element: 22 23 24 25 26 27 28 29 30
---------------- addFuncObject(): Run End ----------------

 

C++ 11 - STL - 函数对象(Function Object) (中)

标签:

原文地址:http://www.cnblogs.com/davidgu/p/4837740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!