1. 程式人生 > >C++ list結構體變量排序

C++ list結構體變量排序

函數 clas strong 對list排序 iostream har toa std class

以下內容是自己整理的根據結構體裏面的不同變量,對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中直接實現,再次在類的成員函數調用時就不會出錯,具體原因不在此列出,可以自行嘗試。以上內容純屬自我理解,有不準確的地方,請指出留言,相互學習。

C++ list結構體變量排序