5

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

Martin Dvoracek
  • 1,714
  • 6
  • 27
  • 55

4 Answers4

13

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...
});
pestophagous
  • 4,069
  • 3
  • 33
  • 42
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
7

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());
StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
3

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.

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

You can do this by specifying your own comparison function.

Some useful references:

Community
  • 1
  • 1
Marc Claesen
  • 16,778
  • 6
  • 27
  • 62