我用operator()遇到了这段代码.我以前从未见过这个(我见过+,>, - <<).有人可以解释何时应该使用它以及如何使用它?
class sortResults
{
public:
bool operator() (Result const & a, Result const & b);
};
Run Code Online (Sandbox Code Playgroud)
这被称为仿函数(不要与函数编程语言中的仿函数混淆).
它模仿一个函数,可以在标准库中的函数中使用:
std::vector<Result> collection;
// fill with data
// Sort according to the () operator result
sortResults sort;
std::sort(collection.begin(), collection.end(), sort);
Run Code Online (Sandbox Code Playgroud)
与简单函数相比,一个很好的优点是它可以保存状态,变量等.您可以与闭包并行(如果响铃)
struct GreaterThan{
int count;
int value;
GreaterThan(int val) : value(val), count(0) {}
void operator()(int val) {
if(val > value)
count++;
}
}
std::vector<int> values;
// fill fill fill
GreaterThan gt(4);
std::for_each(values.begin(), values.end(), gt);
// gt.count now holds how many values in the values vector are greater than 4
Run Code Online (Sandbox Code Playgroud)