说明:
下面程序给出了如何对自定义结构的特殊排序,主要利用STL中的sort排序算法完成。
#include "stdafx.h"#include#include #include #include #include #include #include #include
#include #include using namespace std;struct tagStudent{ string strName; int nAge;};//自定义谓词函数进行比较//每个比较条件,均需使用“<”,否则程序异常bool lessLength(const tagStudent &a, const tagStudent& b){ if (a.nAge == b.nAge) { //姓名长度相等,则按照字典排序 if (a.strName.length() == b.strName.length()) { return a.strName < b.strName; } else { return a.strName.length() < b.strName.length(); } } else { return a.nAge < b.nAge; }}//使用function中的函数,进行比较,只能重载 vecStudentInfos; ss.clear(); ss.str(str); //提取字符串码流中的信息 while (ss >> strWord) { stTemp.strName = strWord; strWord.clear(); ss >> strWord; stTemp.nAge = atoi(strWord.c_str()); vecStudentInfos.push_back(stTemp); } cout << "sort before:" << endl; vector ::iterator it = vecStudentInfos.begin(); for (; it != vecStudentInfos.end(); ++it) { cout << "(" < strName << "," << it->nAge <<")" << endl; } //方法一:重载< cout << "sort after by dictionary:" << endl; sort(vecStudentInfos.begin(), vecStudentInfos.end(), less ()); for (it = vecStudentInfos.begin(); it != vecStudentInfos.end(); ++it) { cout << "(" < strName << "," << it->nAge <<")" << endl; } //方法二:谓词函数 cout << "sort after by string length:" << endl; sort(vecStudentInfos.begin(), vecStudentInfos.end(), lessLength); for (it = vecStudentInfos.begin(); it != vecStudentInfos.end(); ++it) { cout << "(" < strName << "," << it->nAge <<")" << endl; } return 0;}