Attemptimg to use a predicate function causes the error: 'std::sort' no matching overloaded function found

Attemptimg to use a predicate function causes the error: 'std::sort' no matching overloaded function found

我正在尝试将 std::sort() 算法与自定义谓词一起使用,但出现编译器错误。我将 Visual Studio 2019 与 C++17 和 v142 工具集一起使用。

我正在复制 Microsoft Documentation example 中的确切代码。代码如下:

谓词函数:

bool UDgreater ( int elem1, int elem2 )
{
    return elem1 > elem2;
}

主要内容:

for (int i = 0; i < 5; i++) {
    v1.push_back(2 * i + 1);
}

std::sort( v1.begin( ), v1.end( ), UDgreater );

错误:

std::sort() 行遇到谓词函数本身的错误:

'UDgreater' non-standard syntax; use '&' to create a pointer to member`

除了 <algorithm><vector>.

之外,我的测试项目中不存在其他代码

有什么办法可以解决这个问题吗?

错误消息告诉我们您的 UDgreater() 不是一个独立的函数,而是一个 非静态 class 方法 (你没有提到的一个重要细节)。

作为非静态 class 方法,它不能 DIRECTLY 用作标准算法的谓词。您必须使用仿函数(C++11 之前)或 lambda(C++11 及更高版本)来包装它,例如:

// using a functor...

struct UDgreaterFunctor
{
    YourClassType &myClass;

    UDgreaterFunctor(YourClassType &aMyClass) : myClass(aMyClass) {}

    bool operator()(int elem1, int elem2) const {
        return myClass.UDgreater(elem1, elem2);
    }
};

std::sort( v1.begin(), v1.end(), UDgreaterFunctor(*this) );
// using a lambda...

std::sort( v1.begin(), v1.end(),
    [this](int elem1, int elem2){
        return this->UDgreater(elem1, elem2);
    }
);

将UD变大如下:

struct {
    bool operator()(int a, int b) const
    {   
         return a > b;
     }   
 } UDgreater;