problem sorting using member function as comparator

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 } 

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

Leave a Comment