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中直接实现,再次在类的成员函数调用时就不会出错,具体原因不在此列出,可以自行尝试。以上内容纯属自我理解,有不准确的地方,请指出留言,相互学习。

    发上等愿,结中等缘,享下等福;择高处立,就平处坐,向宽处行。
  • 相关阅读:
    ubuntu 源
    20121211 mysqld.sock丢失无法启动mysql和登陆
    hadoop0.20.2 & hbase0.90.1 集群启动错误“org.apache.hadoop.ipc.RPC$VersionMismatch: Protocol org.apache.hadoop.hdfs.protocol.ClientP
    20121204当前集群的几个问题
    hive中的bucket table (输入文件是一个的话,map任务只能启动一个 ,给力啊)
    Android的animation
    获取已安装程序的名字、包名
    android布局属性
    Ghost网络克隆详细步骤教程
    教你如何用PQ魔法师调整硬盘分区大小【图解教程】
  • 原文地址:https://www.cnblogs.com/lyx5990/p/9455530.html
Copyright © 2011-2022 走看看