仿函数
仿函数(functor),其实就是定义了运算符()的类。
struct
{
void operator()(const int & x)
{
}
};
例如:
假设有一个vector<string>
,你的任务是统计长度小于5的string的个数,如果使用count_if
函数的话,你的代码可能长成这样:
bool LengthIsLessThanFive(const string& str)
{
return str.length() < 5;
}
int res=count_if(vec.begin(), vec.end(), LengthIsLessThanFive);
一般的,如果需要将特定的阈值长度也传入的话,我们可能将函数写成这样:
bool LenthIsLessThan(const string& str, int len)
{
return str.length() < len;
}
这个函数看起来比前面一个版本更具有一般性,但是他不能满足count_if
函数的参数要求:count_if
要求的是unary function(仅带有一个参数)作为它的最后一个参数。所以问题来了,怎么样找到以上两个函数的一个折中的解决方案呢?
使用仿函数
class ShorterThan
{
public:
explicit ShorterThan(int maxLength) : length(maxLength) {}
bool operator() (const string& str) const
{
return str.length() < length;
}
private:
const int length;
};
count_if(myVector.begin(), myVector.end(), ShorterThan(length));//直接调用即可