C++ 11

1. 预定义函数对象

C++标准库内含许多预定义的函数对象,也就是内置的函数对象。

你可以充分利用他们,不必自己费心去写一些自己的函数对象。

要使用他们,你只要包含如下头文件

#include <functional>

eg:

set<int, less<int>> coll;  // sort elements with <

set<int, greater<int>> coll;  // sort elements with >

predefinedFuncObjectTest.cpp

deque<int> coll = { 1, 2, 3, 5, 7, 11, 13, 17, 19 };

PRINT_ELEMENTS(coll, "initialized: ");

// negate all values in coll
transform(coll.cbegin(), coll.cend(),      // source
    coll.begin(),                   // destination
    negate<int>());                 // operation
PRINT_ELEMENTS(coll, "negated:     ");

// square all values in coll
transform(coll.cbegin(), coll.cend(),      // first source
    coll.cbegin(),                  // second source
    coll.begin(),                   // destination
    multiplies<int>());             // operation
PRINT_ELEMENTS(coll, "squared:     ");

运行结果:

---------------- predefinedFuncObject(): Run Start ----------------
initialized: 1 2 3 5 7 11 13 17 19
negated:     -1 -2 -3 -5 -7 -11 -13 -17 -19
squared:     1 4 9 25 49 121 169 289 361
---------------- predefinedFuncObject(): Run End ----------------

2. 预定义函数对象绑定

你可以使用binder将预定义函数对象和其他数值进行绑定。

pdFuncObjectBind.cpp

using namespace std::placeholders;

set<int, greater<int>> coll1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
deque<int> coll2;

// Note: due to the sorting criterion greater<>() elements have reverse order:
PRINT_ELEMENTS(coll1, "initialized: ");

// transform all elements into coll2 by multiplying them with 10
transform(coll1.cbegin(), coll1.cend(),      // source
    back_inserter(coll2),             // destination
    bind(multiplies<int>(), _1, 10));   // operation
PRINT_ELEMENTS(coll2, "transformed: ");

// replace value equal to 70 with 42
replace_if(coll2.begin(), coll2.end(),       // range
    bind(equal_to<int>(), _1, 70),     // replace criterion
    42);                             // new value
PRINT_ELEMENTS(coll2, "replaced:    ");

// remove all elements with values between 50 and 80
coll2.erase(remove_if(coll2.begin(), coll2.end(),
    bind(logical_and<bool>(),
    bind(greater_equal<int>(), _1, 50),
    bind(less_equal<int>(), _1, 80))),
    coll2.end());
PRINT_ELEMENTS(coll2, "removed:     ");

运行结果:

---------------- pdFuncObjectBind(): Run Start ----------------
initialized: 9 8 7 6 5 4 3 2 1
transformed: 90 80 70 60 50 40 30 20 10
replaced:    90 80 42 60 50 40 30 20 10
removed:     90 42 40 30 20 10
---------------- pdFuncObjectBind(): Run End ----------------

原文地址:https://www.cnblogs.com/davidgu/p/4846327.html