• 自定义数据类型使用sort排序


     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 struct tree{
     5     string zfc;
     6     int a;
     7     /*bool operator<(const tree &a) 
     8     {
     9         if(zfc<a.zfc)
    10         return true;
    11         else if(zfc==a.zfc)
    12         {
    13             return this->a<a.a;
    14         }
    15         return false;
    16     }*/
    17     /* 这里的const 和&都可以省略*/
    18 };
    19 /* 随便写在里面外面,加不加const和&都不影响sort排序*/
    20 bool operator<(tree a,tree b)
    21 {
    22     if(a.zfc<b.zfc)
    23     return true;
    24     else if(a.zfc==b.zfc)
    25     {
    26         return a.a<b.a;
    27     }
    28     return false;
    29 }
    30 bool cmp(tree a,tree b)
    31 {
    32     if(a.zfc<b.zfc)
    33     return true;
    34     else if(a.zfc==b.zfc)
    35     {
    36         return a.a<b.a;
    37     }
    38     return false;
    39 } 
    40 int main()
    41 {
    42     tree t[3];
    43     t[0].zfc="hh";
    44     t[0].a=1;
    45     t[1].zfc="xx";
    46     t[1].a=2;
    47     t[2].zfc="hh";
    48     t[2].a=0;
    49 //    sort(t,t+3);
    50     sort(t,t+3,cmp);
    51     /* 使用sort既可以重载元素类型的比较符号,也可以自己写新的排序函数*/
    52     for(int i=0;i<3;i++)
    53     {
    54         cout<<t[i].zfc<<" "<<t[i].a<<endl;
    55     }
    56 }

    3个比较方式,随便一个都可以。

  • 相关阅读:
    2019.1.8兔子问题和汉诺塔问题的解决代码
    REST
    存储过程和函数练习
    十六、性能优化
    十五、MySQl日志
    Shell入门
    十四、数据备份
    十三、MySQL触发器
    十二、视图
    十一、MySQL锁
  • 原文地址:https://www.cnblogs.com/dayq/p/11939095.html
Copyright © 2020-2023  润新知