在STL里,常常用到函数对象。关键是要重载()运算符。
从class TFuncObj
{
public:
TFuncObj(int value) : m_value(value)
{
}
//重载()运算符
bool operator()(int item) { return item == value;}
public:
int m_value;
};
测试的例子:
#include <vector>
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
std::vector<int>::iterator ret;
ret = find_if(v.begin(),v.end(),TFuncObj(3));
if ( ret != v.end() )
{
printf(" find obj = %d/n",*ret);
}
else
{
printf(" not find obj/n");
}
怎样很简单吧。当然,这个例子体现不了函数对象的强大功能。当容器里的对象不是简单类型时,而且重载对象的==运算符不能满足要求时,函数对象就是一个很好的选择。