简体   繁体   中英

Using stable_sort, when sorting vector of objects

I have class Passanger that has variables string name; string station; string ticket; 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM