Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using stable_sort, when sorting vector of objects

Tags:

c++

stl

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() ); ?

like image 775
Martin Dvoracek Avatar asked May 18 '13 13:05

Martin Dvoracek


4 Answers

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...
});
like image 111
Andy Prowl Avatar answered Nov 05 '22 14:11

Andy Prowl


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());
like image 36
StilesCrisis Avatar answered Nov 05 '22 13:11

StilesCrisis


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.

like image 3
hmjd Avatar answered Nov 05 '22 13:11

hmjd


You can do this by specifying your own comparison function.

Some useful references:

  • stable_sort documentation (cfr. the code example for the example comparison function bool compare_as_ints (double i,double j) )
  • functors and their uses
like image 1
Marc Claesen Avatar answered Nov 05 '22 14:11

Marc Claesen