Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
218 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...