排序问题,STL中默认是采用小于号来排序的,因为设置int等类型做key,它本身支持小于号运算,在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过不去,下面给出两个方法解决这个问题:
第一种:小于号重载,程序举例
1 #include <map> 2 #include <string> 3 using namespace std; 4 typedef struct tagStudentInfo 5 { 6 int nID; 7 string strName; 8 }StudentInfo, *PStudentInfo; //学生信息 9 10 int main() 11 { 12 int nSize; //用学生信息映射分数 13 map<StudentInfo, int>mapStudent; 14 map<StudentInfo, int>::iterator iter; 15 StudentInfo studentInfo; 16 studentInfo.nID = 1; 17 studentInfo.strName = “student_one”; 18 mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90)); 19 studentInfo.nID = 2; 20 studentInfo.strName = “student_two”; 21 22 mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80)); 23 for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++) 24 cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl; 25 } 26 //以上程序是无法编译通过的,只要重载小于号,就OK了,如下: 27 28 typedef struct tagStudentInfo 29 { 30 int nID; 31 string strName; 32 Bool operator < (tagStudentInfo const& _A) const 33 { 34 //这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序 35 if(nID < _A.nID) return true; 36 if(nID == _A.nID) return strName.compare(_A.strName) < 0; 37 return false; 38 } 39 }StudentInfo, *PStudentInfo; //学生信息
第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明
1 #include <map> 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 6 typedef struct tagStudentInfo 7 { 8 int nID; 9 string strName; 10 }StudentInfo, *PStudentInfo; //学生信息 11 12 class sort{ 13 public: 14 bool operator() (StudentInfo const & _A, StudentInfo const & _B) const 15 { 16 if(_A.nID < _B.nID){ 17 return true; 18 }else if (_A.nID == _B.nID){ 19 return _A.strName.compare(_B.strName) < 0; 20 } 21 return false; 22 } 23 }; 24 25 int main() 26 { 27 int nSize; //用学生信息映射分数 28 map<StudentInfo, int, sort> mapStudent; 29 StudentInfo studentInfo; 30 studentInfo.nID = 1; 31 studentInfo.strName = "student_one"; 32 33 mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90)); 34 studentInfo.nID = 2; 35 studentInfo.strName = "tudent_two"; 36 mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80)); 37 38 std::map<StudentInfo, int, sort>::iterator it; 39 for(it = mapStudent.begin(); it != mapStudent.end(); it++){ 40 std::cout << it->second << std::endl; 41 } 42 }