为什么我们将 greater<string>() 传递给排序算法?

Why do we pass greater<string>() to the sort algorithm?

据我所知,Functor 基本上是一个覆盖 operator () 的 class。现在我必须首先实例化一个 class,以使用覆盖运算符。例如 -

class A {
    bool operator()(int a, int b) const {
        return a<b;
    }
}

现在,当我想将其传递给排序函数时,我首先必须实例化它。

A instance;
sort(a.begin(),a.end(),instance);

以上应该是正确的实现,因为我正在将一个函数传递给排序函数,它可以用于比较。为什么我必须将 instance() 作为参数而不是实例传递。

还有一件事:当我传递类似 greater() 的东西时,我什至没有实例化 class!

Why do I have to pass instance() as argument instead of instance.

你不知道。

要么传递 instance(实例的名称),要么传递 A()(这是一个单独的临时实例)。

One more thing , when I pass something like greater(), I am not even instantiating the class !

当然是。这是 greater.

类型的临时文件

别忘了让您的 operator() 成为 public

std::greater是一个函数对象,它是一个提供函数调用运算符的结构。

表达式

std::greater<std::string>()

调用结构的构造函数并创建类型为 std::greater<std::string> 的临时对象,可以在算法中为其调用函数调用运算符。

相对于你的函数对象定义

class A {
    bool operator()(int a, int b) const {
        return a<b;
    }
}

要创建 class 的实例,您应该使用表达式

A()

所以你可以这样写

std::sort( a.begin(), a.end(), A() );

A instance;
std::sort( a.begin(), a.end(), instance );

考虑到这些代码片段的结果是等价的

std::cout << A()( 10, 20 ) << std::endl;

A instance;

std::cout << instance( 10, 20 ) << std::endl;