//
// 学习仿函数的用法, 以及与函数适配器,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();
}