使用成员函数作为比较器进行排序的问题

2021-12-10 00:00:00 sorting compiler-errors c++ stl

尝试编译以下代码时出现此编译错误,我该怎么办?

trying to compile the following code I get this compile error, what can I do?

ISO C++ 禁止取地址不合格的或括号内的非静态成员函数形成一个指向成员函数的指针.

ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.

class MyClass {
   int * arr;
   // other member variables
   MyClass() { arr = new int[someSize]; }

   doCompare( const int & i1, const int & i2 ) { // use some member variables } 

   doSort() { std::sort(arr,arr+someSize, &doCompare); }

}; 

推荐答案

doCompare 必须是 static.如果 doCompare 需要来自 MyClass 的数据,您可以通过更改将 MyClass 变成一个比较函子:

doCompare must be static. If doCompare needs data from MyClass you could turn MyClass into a comparison functor by changing:

doCompare( const int & i1, const int & i2 ) { // use some member variables } 

进入

bool operator () ( const int & i1, const int & i2 ) { // use some member variables } 

并调用:

doSort() { std::sort(arr, arr+someSize, *this); }

另外,doSort 是不是缺少返回值?

Also, isn't doSort missing a return value?

我认为应该可以使用 std::mem_fun 和某种绑定将成员函数转换为自由函数,但目前我无法理解确切的语法.

I think it should be possible to use std::mem_fun and some sort of binding to turn the member function into a free function, but the exact syntax evades me at the moment.

Doh,std::sort 按值获取函数,这可能是一个问题.为了解决这个问题,将函数包装在类中:

Doh, std::sort takes the function by value which may be a problem. To get around this wrap the function inside the class:

class MyClass {
    struct Less {
        Less(const MyClass& c) : myClass(c) {}
        bool operator () ( const int & i1, const int & i2 ) {// use 'myClass'} 
        MyClass& myClass;
    };
    doSort() { std::sort(arr, arr+someSize, Less(*this)); }
}

相关文章