zoukankan      html  css  js  c++  java
  • C++ list结构体变量排序

    以下内容是自己整理的根据结构体里面的不同变量,对list排序的实例,若有问题可以留言。仅供参考。

     1 #include <iostream>
     2 #include <list>
     3 #include <algorithm>
     4 
     5 using namespace std;
     6 
     7 //声明结构体
     8 typedef struct testListSort
     9 { 
    10   int number; 
    11   std::string name;
    12   char time[10]; 
    13   int datalen; 
    14 }stuTest;
    15 
    16 //结构体list
    17 std::list<stuTest> listDataInfo;
    18 
    19 //比较函数:根据结构体里面的整型number排序
    20 bool sortStuInt(const stuTest& m1, const stuTest& m2)
    22 {
    23 
    24   return m1.number < m2.number;
    25 }
    26 
    27 //比较函数:根据结构体里面的字符串name排序
    28 bool comStuString(const stuTest& m1, const stuTest& m2)
    30 {
    31   if(m1.name.compare(m2.name) <= 0)
    32   {
    33     return true;
    34   }
    35   else
    36   {
    37     return false;
    38   }
    39 }
    40 
    41 int main(void)
    42 {
    43   //仅对结构体里面的
    44   for (int i = 0; i < 10; i++)
    45   {
    46     //结构体整型赋值
    47     stuTest temp;
    48     temp.number = rand()%100;
    49 
    50     //结构体字符串赋值
    51     int num = rand()%100;
    52     char strChar[10];
    53     itoa(num,strChar,10);
    54     temp.name = strChar;
    55 
    56     listDataInfo.push_back(temp);
    57   }
    58 
    59   //按照结构体里面的整型数据,对list里面结构体排序
    60   listDataInfo.sort(sortStuInt);
    61 
    62   //按照结构体里面的字符串数据,对list里面结构体排序
    63   //listDataInfo.sort(comStuString);
    64 
    65   return 0;
    66 }

    以上仅是对单个文件里面的list 按照结构体变量排序,如果在类的成员变量中,声明上述比较函数sortStuInt、comStuString,并且在类的其他成员函数调用的话,可能会有问题,这时可以把比较函数放到类前声明,在类的CPP中直接实现,再次在类的成员函数调用时就不会出错,具体原因不在此列出,可以自行尝试。以上内容纯属自我理解,有不准确的地方,请指出留言,相互学习。

    发上等愿,结中等缘,享下等福;择高处立,就平处坐,向宽处行。
  • 相关阅读:
    【HDOJ6666】Quailty and CCPC(模拟)
    【2019 Multi-University Training Contest 8】
    分布式锁的理解
    反射工具类【ReflectionUtils】
    Maven常用命令
    maven常用命令介绍
    mysql 优化策略(如何利用好索引)
    centos7搭建svn服务器及客户端设置
    Centos7 配置subversion
    Centos7更改网卡名称Eth0
  • 原文地址:https://www.cnblogs.com/lyx5990/p/9455530.html
Copyright © 2011-2022 走看看