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,670
  • 6
  • 26
  • 54

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
  • 3,919
  • 3
  • 34
  • 41
Andy Prowl
  • 119,862
  • 22
  • 374
  • 446
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,646
  • 4
  • 35
  • 58
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
  • 117,013
  • 19
  • 199
  • 247
1

You can do this by specifying your own comparison function.

Some useful references:

Community
  • 1
  • 1
Marc Claesen
  • 16,248
  • 6
  • 26
  • 61