Virtual Methods as a Comp Function for Sorting

I am new to C ++ and I am trying to use the std :: sort function to sort the solution vector.

The code looks something like this (the list of solutions is a vector *):

void SolutionSet::sort(Comparator &comparator) { std::sort(solutionsList_->begin(), solutionsList_->end(), &comparator::compare); } 

The comparator parameter is an instance of the Comparator child class, and the comparison method is virtual in the Comparator class and is implemented by all comparator child classes.

And I want to use this function as a comparator function in std: sort ().

Is it possible?

If so, can someone tell me how? Because it does not work with the previous code.

If I do not understand myself, just ask!

Thanks guys!

+4
source share
2 answers

STL functors must be monomorphic because STL functions are passed by value.

If you need polymorphic behavior, you need to wrap this 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); } }; 
+5
source

You should use std :: bind as Comparator :: compare - the instance method, so you need a Comparator object as a parameter.

Something like that:

 std::sort (...., std::bind (&Comparator::compare, comparator)); 
+1
source

Source: https://habr.com/ru/post/1308034/


All Articles