C++ 11 - STL - 函式物件(Function Object) (下)

weixin_33766168發表於2015-09-29

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

 

相關文章