• C++ 11


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

    需求:

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

    代码如下:

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

  • 相关阅读:
    React.js自学第一天
    优化的34条定律
    JS 打字机效果
    css3 翻书效果
    对象操作
    表单提交验证
    封装cookie组件
    iOS中为网站添加图标到主屏幕
    教你从Win8换回Win7
    关于VB中Print函数在数组中换行的理解
  • 原文地址:https://www.cnblogs.com/davidgu/p/4837740.html
Copyright © 2020-2023  润新知