problem sorting using member function as comparator(使用成员函数作为比较器进行排序的问题)
问题描述
尝试编译以下代码时出现此编译错误,我该怎么办?
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)); }
}
这篇关于使用成员函数作为比较器进行排序的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用成员函数作为比较器进行排序的问题


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01