使用成员函数作为比较器的问题排序 [英] problem sorting using member function as comparator

查看:320
本文介绍了使用成员函数作为比较器的问题排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图编译以下代码我得到这个编译错误,我能做什么?







ISO C ++禁止使用
的地址作为非限定或括号的
非静态成员函数,以形成一个指向成员函数的
指针。




  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

编辑: Doh, 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?


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

这篇关于使用成员函数作为比较器的问题排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆