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

简介: 我们再来看一个复杂的例子 需求: 我们需要对集合内每个元素加上一个特定的值 代码如下: AddInt.h class AddInt { private: int theValue; // the value to add public: // const...

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

需求:

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

代码如下:

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

 

目录
相关文章
|
1天前
|
存储 搜索推荐 C++
【C++高阶(二)】熟悉STL中的map和set --了解KV模型和pair结构
【C++高阶(二)】熟悉STL中的map和set --了解KV模型和pair结构
|
1天前
|
设计模式 C语言 C++
【C++进阶(六)】STL大法--栈和队列深度剖析&优先级队列&适配器原理
【C++进阶(六)】STL大法--栈和队列深度剖析&优先级队列&适配器原理
|
1天前
|
存储 缓存 编译器
【C++进阶(五)】STL大法--list模拟实现以及list和vector的对比
【C++进阶(五)】STL大法--list模拟实现以及list和vector的对比
|
1天前
|
算法 C++ 容器
【C++进阶(四)】STL大法--list深度剖析&list迭代器问题探讨
【C++进阶(四)】STL大法--list深度剖析&list迭代器问题探讨
|
1天前
|
编译器 C++
【C++进阶(三)】STL大法--vector迭代器失效&深浅拷贝问题剖析
【C++进阶(三)】STL大法--vector迭代器失效&深浅拷贝问题剖析
|
1天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
2天前
|
存储 算法 C语言
c++的学习之路:9、STL简介与string(1)
c++的学习之路:9、STL简介与string(1)
19 0
|
2天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
2天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
17 0
|
7天前
|
编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”

热门文章

最新文章