天天看點

仿函數, 函數擴充卡,與STL算法的配合使用

//

// 學習仿函數的用法, 以及與函數擴充卡,STL算法的配合使用

#include <iostream>

#include <algorithm>

#include <string>

#include <functional>

using namespace std;

// 仿函數(functor), 或稱函數對象(function object),

// 用于給find_if函數提供判斷式(謂詞predicate)

template<class T1, class T2>

struct ftor : public binary_function<T1, T2, bool>

{

string str;

public:

ftor(const string& s) { str = s; }

bool operator() (T1 index, T2 value) const

{

return str[index] == value;

}

};

int main()

{

int arr[9] = {0,1,2,3,4,5,6,7,8};

string str = "1234567";

// 通過string中的char元素和int數組中的int元素映射,

// 來找到string中的特定元素。

// bind2nd函數用于将2元仿函數判斷式轉換成1元判斷式。

int* result = find_if(arr, arr+9, bind2nd(ftor<int, char>(str), '5'));

if(result != arr+9)

cout << "find char 5 at pos" << *result << endl;

else

cout << "cannot find char 5" << endl;

cin.get();

}

繼續閱讀