开发者

Sorting an STL vector on two values

开发者 https://www.devze.com 2023-03-21 17:06 出处:网络
How do I sort an STL vector based on two different comparison criterias? The default s开发者_StackOverflowort() function only takes a single sorter object.You need to combine the two criteria into one

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消