C++ 11 - STL - 函数对象(Function Object) (中)
2015-09-25 11:46
513 查看
我们再来看一个复杂的例子
需求:
我们需要对集合内每个元素加上一个特定的值
代码如下:
AddInt.h
设置一个打印模板类
print.hpp
测试程序:
运行结果:
---------------- 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 ----------------
需求:
我们需要对集合内每个元素加上一个特定的值
代码如下:
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 ----------------
相关文章推荐
- Objective-C---3---NSString的常用方法
- 设计模式之工厂方法模式(代码用Objective-C展示)
- Java学习笔记【Object】
- 【投稿】打造Objective-C安全的Collection类型
- Object-C 对象初始化
- Object-C 数组(一)(NSArray)
- Object-C 字符串对象
- object-c 字符串(NSString)
- 【IOS 开发学习总结-OC-18】★★objective-c面向对象之——OC的包装类与对象处理
- org.hibernate.NonUniqueObjectException的原因与解决方法
- 黑马程序员--Java基础学习笔记【Object类、String类】
- Object 转 Json (针对父类和数组)
- Objective C静态代码扫描和代码质量管理 OClint + SonarQube
- 2016校招记
- 操作JSONObject中的某一个bean
- 获取JSONObject里所有key
- 【IOS 开发学习总结-OC-17】★★objective-c面向对象之——多态
- Object-c 面向对象(四)
- Object-c 面向对象(三)
- Object-c 面向对象(二)