简体   繁体   中英

C++ sort vector using non-static member function

I have a class called Sorter . It has two public items.

  1. int type variable choice
  2. member function called compare with a int type return value that accepts two objects as parameter.

I tried creating an instance of Sorter while passing choice with a value to the constructor,

Then i wanted to use C++ sort function to sort a vector . and to pass the member function compare of the instance i created.

The compare member function uses the variable choice to decide the sorting mechanism.

But i was not able to get the pointer to the member function compare of an instance of Sorter .

Could someone advice me on this?

If you can change the structure of your Sorter class, you could make it a function object by defining operator () like this:

bool Sorter::operator ()(const MyObject &o1, const MyObject &o2) {
  // return true if o1 < o2
}

Then you can just pass an instance of your Sorter class to std::sort .

Unfortunately, the standard library is a bit lacking in combinators for things like this. However, boost::lambda can do the job:

#include <boost/lambda/bind.hpp>

namespace l = boost::lambda;

struct foo {
    bool bar(char, char);
};


void test(foo *pFoo) {
    char a[2] = {0};

    std::sort(a, a+1,
            l::bind(&foo::bar, pFoo, l::_1, l::_2));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM