zoukankan      html  css  js  c++  java
  • 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 ----------------

  • 相关阅读:
    树链剖分总结
    主席树总结
    BZOJ1053:反素数(数学)
    CH3101 阶乘分解
    2018-2019 ACM-ICPC ECfinal I. Misunderstood … Missing
    洛谷P3201 [HNOI2009]梦幻布丁(链表 + 启发式合并)
    Codeforces Round #552 (Div. 3) 题解
    线段树合并 总结
    生成器
    Python中input()和raw_input()的区别
  • 原文地址:https://www.cnblogs.com/davidgu/p/4837740.html
Copyright © 2011-2022 走看看