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

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

需求:

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

代码如下:

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 ----------------

 

posted @ 2015-09-25 11:46  Master HaKu  阅读(247)  评论(0编辑  收藏  举报