c++ - 使用成员函数作为比较器的问题排序

标签 c++ sorting stl compiler-errors

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


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( 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 不是缺少返回值吗?

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

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

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)); }
}

关于c++ - 使用成员函数作为比较器的问题排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1902311/

相关文章:

c++ - 将结果存储在 C++ 文件中

c# - 将 C# 哈希函数转换为 C++

java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : -1 (Sort Condition)

c++ - 任何人都有一个很好的 C++ 共享内存容器?

c++ - 将一张 map 的内容附加和替换到另一张 map ?

c++ - 一行中的最后一个数组元素和下一行中具有相同指针的第一个元素

c++ - OpenCV C++ : Sorting contours by their contourArea

Android - 更原始的数组仅按一个数组排序

c++ - 从 std::set 中提取仅 move 类型

c++ - x > y > new T : syntax 的可能含义