1. 预定义函数对象
C++标准库内含许多预定义的函数对象,也就是内置的函数对象。
你可以充分利用他们,不必自己费心去写一些自己的函数对象。
要使用他们,你只要包含如下头文件
#include <functional>
eg:
set<int, less<int>> coll; // sort elements with <
set<int, greater<int>> coll; // sort elements with >
predefinedFuncObjectTest.cpp
deque coll = { 1, 2, 3, 5, 7, 11, 13, 17, 19 };PRINT_ELEMENTS(coll, "initialized: ");// negate all values in colltransform(coll.cbegin(), coll.cend(), // source coll.begin(), // destination negate ()); // operationPRINT_ELEMENTS(coll, "negated: ");// square all values in colltransform(coll.cbegin(), coll.cend(), // first source coll.cbegin(), // second source coll.begin(), // destination multiplies ()); // operationPRINT_ELEMENTS(coll, "squared: ");
运行结果:
---------------- predefinedFuncObject(): Run Start ----------------
initialized: 1 2 3 5 7 11 13 17 19negated: -1 -2 -3 -5 -7 -11 -13 -17 -19squared: 1 4 9 25 49 121 169 289 361---------------- predefinedFuncObject(): Run End ----------------
2. 预定义函数对象绑定
你可以使用binder将预定义函数对象和其他数值进行绑定。
pdFuncObjectBind.cpp
using namespace std::placeholders;set