以下内容是自己整理的根据结构体里面的不同变量,对list排序的实例,若有问题可以留言。仅供参考。
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
//声明结构体
typedef struct testListSort
{          
	  int number; 
	  std::string name;
	  char time[10];                 
	  int datalen;                  
}stuTest;
//结构体list
std::list<stuTest> listDataInfo;
//比较函数:根据结构体里面的整型number排序
bool sortStuInt(const stuTest& m1, const stuTest& m2)
{
	  return m1.number < m2.number;
}
//比较函数:根据结构体里面的字符串name排序
bool comStuString(const stuTest& m1, const stuTest& m2)
 {
	  if(m1.name.compare(m2.name) <= 0)
	  {
		    return true;
	  }
	  else
	  {
		    return false;
	  }
}
int main(void)
{
	//仅对结构体里面的
	for (int i = 0; i < 10; i++)
	{
		//结构体整型赋值
		stuTest temp;
		temp.number = rand()%100;
		//结构体字符串赋值
		int num = rand()%100;
		char strChar[10];
		itoa(num,strChar,10);
		temp.name = strChar;
		listDataInfo.push_back(temp);
	}
	//按照结构体里面的整型数据,对list里面结构体排序
	listDataInfo.sort(sortStuInt);
	//按照结构体里面的字符串数据,对list里面结构体排序
	//listDataInfo.sort(comStuString);
	return 0;
}
以上仅是对单个文件里面的list 按照结构体变量排序,如果在类的成员变量中,声明上述比较函数sortStuInt、comStuString,并且在类的其他成员函数调用的话,可能会有问题,这时可以把比较函数放到类前声明,在类的CPP中直接实现,再次在类的成员函数调用时就不会出错,具体原因不在此列出,可以自行尝试。以上内容纯属自我理解,有不准确的地方,请指出留言,相互学习。
原文:https://www.cnblogs.com/lyx5990/p/9455530.html