17

How do I sort an STL vector based on two different comparison criterias? The default sort() function only takes a single sorter object.

toastie
  • 1,934
  • 3
  • 22
  • 35
  • Can you elaborate more ? What criteria you want ? – iammilind Jul 21 '11 at 04:55
  • I am sorting a list of objects with two different properties: distance and importance. One of these properties' comparison (higher importance) overrides the other (closer distance). So say if one object's importances is 1 and the other's is 0, it will be sorted higher than the second one even if the distance is larger. I can't figure out a way to do it with just one comparison. – toastie Jul 21 '11 at 05:03

1 Answers1

35

You need to combine the two criteria into one. Heres an example of how you'd sort a struct with a first and second field based on the first field, then the second field.

#include <algorithm>

struct MyEntry {
  int first;
  int second;
};

bool compare_entry( const MyEntry & e1, const MyEntry & e2) {
  if( e1.first != e2.first)
    return (e1.first < e2.first);
  return (e1.second < e2.second);
}

int main() {
  std::vector<MyEntry> vec = get_some_entries();
  std::sort( vec.begin(), vec.end(), compare_entry );
}

NOTE: implementation of compare_entry updated to use code from Nawaz.

Community
  • 1
  • 1
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
  • +1, Straight forward. I thought the same way. But still doubt if the OP is thinking in the same lines. – iammilind Jul 21 '11 at 05:00
  • Great, that worked, thank you! I forgot the if( e1.first == e2.first ) part, so it was failing for me. – toastie Jul 21 '11 at 05:14
  • 2
    @Michael: I added another implementation of `compary_entry` function. Hope its okay with you. :-) +1 BTW. – Nawaz Jul 21 '11 at 05:22
  • +1 Nawaz - I like that change. I was sure it could be a little neater .. and you got it perfect. – Michael Anderson Jul 21 '11 at 05:39
  • I personally prefer `return e1.first != e2.first ? e1.first < e2.first : e1.second < e2.second;`, but each to their own ;-). Separately, if the types support a single query indicating less-than, equals or greater-than (like `strcmp`), this can sometimes be significantly more efficient: `switch (e1.first.cmp(e2.first)) { case -1: return true; case 0: return e1.second < e2.second; case 1: return false; }` (assuming -1/0/1 values, some cmps just promise -ve/0/+ve and the implementation varies accordingly). – Tony Delroy Jul 21 '11 at 06:24