vector自定义比较函数

这里就结构体类型的vector数组以及结构体类型元素比较来自定义cmp比较函数;

 1 #include <algorithm>
 2 ...
 3 struct Node{
 4  int id;
 5  string name;
 6  int age;
 7 }node[100];
 8 bool cmp(Node a,Node b){
 9      if(a.age!=b.age) return a.age<b.age;
10      if(a.id!=b.id) return a.id<b.id;
11      return strcmp(a.chr,b.chr)<0;
12 //    if(a.age<b.age) return true;
13 //    else if(a.age==b.age)
14 //    {
15 //        if(a.id<b.id) return true;
16 //        else if(a.id==b.id)
17 //        {
18 //            if(a.chr<b.chr) return true;
19 //        }
20 //    }
21 //    return false;
22 }
23 vector<Node> vec;
24 ...
25 sort(vec.begin(),vec.end(),cmp);
26 ...

 

posted @ 2021-02-03 23:45  yyer  阅读(853)  评论(0编辑  收藏  举报