I have class Passanger
that has variables string name; string station; string ticket;
and then I have another class and within this class I have vector<Passanger*> myQueue;
now I want to use stable_sort
to sort myQueue
. Is there any possibility, how to say to stable_sort
, what should be the key, according to it shall sort myQueue
?
std::stable_sort(myQueue.begin(),myQueue.end(), maybeSomethingElse() );
?
There is an overload of std::stable_sort()
that accepts a custom comparator as its third argument. You could provide a comparison function there, a functor, or a lambda (in C++11). Going with a lambda, for instance:
std::stable_sort(myQueue.begin(),myQueue.end(), [] (Passenger* p1, Passenger* p2)
{
return p1->age() < p2->age(); // Or whatever fits your needs...
});
Yes, you need a comparator class. They look like this.
class CompareFoo {
public:
bool operator() (const Foo* e1, const Foo* s2)
{
return e1->name < e2->name; // strict weak ordering required
}
};
Then pass an instantiation of it as a parameter to stable_sort
.
std::stable_sort(myQueue.begin(), myQueue.end(), CompareFoo());
Define a comparator using a lambda for example (with std::tie
if the sort is dependent on more than one attribute of Passanger
):
std::stable_sort(myQueue.begin(),
myQueue.end(),
[](Passanger* p1, Passanger* p2)
{
return std::tie(p1->name(), p1->station()) <
std::tie(p2->name(), p2->station());
});
If c++11 is not available define the comparator elsewhere and use boost::tie
.
You can do this by specifying your own comparison function.
Some useful references:
bool compare_as_ints (double i,double j)
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With