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

posted on 2018-08-10 23:04  Freedom_lyx  阅读(5676)  评论(0编辑  收藏  举报