标签:
排序问题,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 <string> 3 using namespace std; 4 typedef struct tagStudentInfo 5 { 6 int nID; 7 string strName; 8 }StudentInfo, *PStudentInfo; //学生信息 9 10 class sort{ 11 public: 12 bool operator() (StudentInfo const &_A, StudentInfo const &_B) const 13 { 14 if(_A.nID < _B.nID){
return true; 15 }else if (_A.nID == _B.nID){
return _A.strName.compare(_B.strName) < 0;
} 16 return false; 17 } 18 }; 19 20 int main() 21 { 22 int nSize; //用学生信息映射分数 23 map<StudentInfo, int, sort>mapStudent; 24 studentInfo studentInfo; 25 studentInfo.nID = 1; 26 studentInfo.strName = "student_one"; 27 28 mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90)); 29 studentInfo.nID = 2; 30 studentInfo.strName = "tudent_two"; 31 mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80)); 32 }
标签:
原文地址:http://www.cnblogs.com/chris-cp/p/5053380.html