1. 程式人生 > >STL仿函式簡單總結

STL仿函式簡單總結

C++相對於C語言來說,有兩個重點,1.面向物件特性;2.函式模板/泛型程式設計。對於STL中的6大元件:容器/演算法/迭代器/仿函式/介面卡/空間配置器。仿函式的用法比較多樣化,下面簡單總結一下。
使用:

    _OutIt copy_if(_InIt _First, _InIt _Last, _OutIt _Dest,
        _Pr _Pred)

這裡_Pr,用於限定copy的條件。如果不符合要求的函式規範,則忽略,進行全copy。

  1. 使用1元普通函式
//1.使用1元函式
bool copyfunc1Param(const int& srcValue)
{
    return
srcValue > 1; }
  1. 使用1元仿函式
//2.使用1元仿函式
class CopyClass1Param :public unary_function<int, bool>
{
public:
    bool operator()(const int value) const
    {
        return value>2;
    }
};
  1. 使用2元普通函式,但通過特殊函式進行轉換
//3.使用2元函式,直接將篩選條件傳遞給函式
bool copyUpNum( int srcValue,int base )
{
    return
srcValue > base; }
  1. 使用2元仿函式,進行函式因子繫結(將2元因子轉化為1元因子)

//4.使用2元仿函式
class CopyClassUpNum : public binary_function<int, int, bool>
{
public:
    bool operator()(const int srcValue, const int base) const
    {
        return srcValue > base;
    }
};

測試用例如下:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream> #include<algorithm> #include<vector> #include<iomanip> #include<functional> using namespace std; int main() { vector<int> srcVec; srcVec.push_back(2); srcVec.push_back(1); srcVec.push_back(3); printIntVector(srcVec); vector<int> targetVec; targetVec.resize(srcVec.size()); //通過copy_if研究仿函式的各種用法(這裡仿函式用於選擇copy的條件) //copy_if(srcVec.begin(), srcVec.end(), targetVec.begin(), copyfunc1Param); //py_if(srcVec.begin(), srcVec.end(), targetVec.begin(), CopyClass1Param()); //使用bind2nd將傳遞的copy標準,繫結到呼叫的仿函式的2nd個引數上, ptr_fun 將普通函式轉化為仿函式 //copy_if(srcVec.begin(), srcVec.end(), targetVec.begin(), bind2nd(ptr_fun(copyUpNum),1)); copy_if(srcVec.begin(), srcVec.end(), targetVec.begin(), bind2nd(CopyClassUpNum(), 2)); printIntVector(targetVec); system("pause"); return EXIT_SUCCESS; }