views:

78

answers:

2

Hello everyone!

I'm new to C++ and i'm trying to use std::sort function to sort a vector of Solutions.

The code is something like this (solution list is a *vector):

void SolutionSet::sort(Comparator &comparator) {

 std::sort(solutionsList_->begin(), solutionsList_->end(), &comparator::compare);

}

The comparator param is a Comparator´s child class instance , and the compare method is virtual at Comparator class and implemented by all Comparator's child classes.

And i want to use that function as a comparator function at std:sort().

Is this possible?

If it is, can someone tell me how? Because with the previous code, it doesn't work.

If i've not made myself clear, please just ask!

Thank you guys!

+1  A: 

You should use std::bind as Comparator::compare is instance method, thus it needs a Comparator object as parameter.

Something like that:

std::sort (...., std::bind (&Comparator::compare, comparator));
buratinas
`std::bind` is in C++0x only.
Billy ONeal
+5  A: 

STL functors are required to be monomorphic because STL functors are passed by value.

If you need polymorphic behavior, you need to wrap that functionality in a monomorphic class:

i.e.

struct MonomorphicWrapper : std::binary_function<Solution, Solution, bool>
{
    bool operator()(const Solution& lhs, const Solution& rhs)
    {
        return lhs.compare(rhs);
    }
};
Billy ONeal
As you can see in my previous post, it is the super class Comparator that compare the two solutions. So this isn't the best solution for me.But i was think of something like this: I could make a structure with tow pointers to two diferent solutions, and use it as the first param to the wrapper, and the comparator instance as the second param. Would this work?
@wilsongoncalo.mp: Yes, you can use the strategy pattern all day long.
Billy ONeal