问题描述
试图编译以下代码我得到这个编译错误,我能做什么?
class MyClass {
int * arr;
//其他成员变量
MyClass(){arr = new int [someSize]; }
doCompare(const int& i1,const int& i2){//使用一些成员变量}
doSort(){std :: sort(arr, arr + someSize,& doCompare); }
};
doCompare
必须 static
。如果 doCompare
需要来自 MyClass
的数据,您可以将 MyClass
一个比较函数通过改变:
doCompare(const int& i1,const int& i2){// use some member变量}
into
bool operator()(const int& i1,const int& i2){//使用一些成员变量}
并调用:
doSort(){std :: sort(arr,arr + someSize,* this); }
此外,不是 doSort
一个返回值?
我认为应该可以使用 std :: mem_fun
std :: sort
通过值获取函子,这可能是一个问题。要绕过这个包装类中的函子: class MyClass {
struct Less {
Less (const MyClass& c):myClass(c){}
bool operator()(const int& i1,const int& i2){// use'myClass'}
MyClass&我的课;
};
doSort(){std :: sort(arr,arr + someSize,Less(* this)); }
}
trying to compile the following code I get this compile error, what can I do?
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
must be static
. If doCompare
needs data from MyClass
you could turn MyClass
into a comparision functor by changing:
doCompare( const int & i1, const int & i2 ) { // use some member variables }
into
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
and calling:
doSort() { std::sort(arr,arr+someSize, *this); }
Also, isn't doSort
missing a return value?
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.
EDIT: Doh, std::sort
takes the functor by value which may be a problem. To get around this wrap the functor 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)); }
}
这篇关于问题排序使用成员函数作为比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!