C++ sort vector using non-static member function
-
16-10-2019 - |
Question
I have a class called Sorter
. It has two public items.
int
type variablechoice
- member function called
compare
with aint
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?
Solution
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
.
OTHER TIPS
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));
}