pointer to member function

Hi All:

When I implement a member function of a class, I want to sort a vector using "sort" defined by stl in <algorithm>.

Every element of the vector to be sorted, is a struct:
1
2
3
4
5
struct Element
{
   int index;
   double value;
};


So I need to provide a sorting function "bool cmpVectorElement(Element first, Element second)" into "sort"
 
sort(my_vector.begin(), my_vector.end(), cmpVectorElement);


I want to define cmpVectorElement() as a protected member function of my class. But compiler gives me error.


I looked it up, and found that class member function pointer is actually different from traditional function pointers.

I know I can define the cmpVectorElement() function as static, as a work-around. But that's not a good solution in my case because I will have a derived class, and in that derived class, it will has its own version of cmpVectorElement(). Static would mean that my derived class will have to share the same cmpVectorElement() function of the base class.


So can anyone point out a solution? I need it to be in accord with good software engineering practice. Thanks!
Last edited on
You could use a functor.
1
2
3
4
5
6
7
8
9
10
11
class compare_element{
private:
  base &how;
public:
  compare_element(base &how):how(how){}
  bool operator()(element a, element b){ 
    how.compare(a,b); //virtual method
  }
};

sort(my_vector.begin(), my_vector.end(), compare_element(some_derived) );


¿Why did I use another class? I guess you could virtualize the parenthesis operator (however then it will need to be public)
Last edited on
Thanks for the reply! I appreciate it.
I have to say this looks elegant.
Nah, elegant is this:

1
2
3
4
5
6
7
#include <boost/lambda/lambda.hpp>

using boost::lambda::_1;
using boost::lambda::_2;


std::sort( my_vector.begin(), my_vector.end(), __1 < __2 );

h9uest wrote:
Static would mean that my derived class will have to share
the same cmpVectorElement() function of the base class.

Mmmm... Not really.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

struct Base           { static void f() { cout << "Base f"    << endl; } };
struct Derived : Base { static void f() { cout << "Derived f" << endl; } };

int main()
{
    Base   ::f();
    Derived::f();

    return 0;
}

h9uest wrote:
I know I can define the cmpVectorElement() function as static, as a work-around.

That's how I would do it by default, not as a workaround.
Last edited on
@jsmith:
Thanks for the fancy boost lamda expression. I'll look a bit more in that.

@m4ster r0shi:
Thanks for pointing out my conceptual mistake. It's helpful.
Topic archived. No new replies allowed.