开发者

Virtual methods as Comp function to sort

开发者 https://www.devze.com 2022-12-28 09:42 出处:网络
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):

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, pleas开发者_Go百科e just ask!

Thank you guys!


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


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

精彩评论

暂无评论...
验证码 换一张
取 消