本文共 2085 字,大约阅读时间需要 6 分钟。
排序问题,STL中默认是采用小于号来排序的,因为设置int等类型做key,它本身支持小于号运算,在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过不去,下面给出两个方法解决这个问题:
1 #include 2 #include 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 mapStudent;14 map ::iterator iter;15 StudentInfo studentInfo;16 studentInfo.nID = 1;17 studentInfo.strName = “student_one”;18 mapStudent.insert(pair (studentInfo, 90));19 studentInfo.nID = 2;20 studentInfo.strName = “student_two”;21 22 mapStudent.insert(pair (studentInfo, 80));23 for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)24 cout< first.nID< < first.strName< < second<
1 #include 2 #include 3 #include 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) const15 {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 mapStudent;29 StudentInfo studentInfo;30 studentInfo.nID = 1;31 studentInfo.strName = "student_one";32 33 mapStudent.insert(pair (studentInfo, 90));34 studentInfo.nID = 2;35 studentInfo.strName = "tudent_two";36 mapStudent.insert(pair (studentInfo, 80));37 38 std::map ::iterator it;39 for(it = mapStudent.begin(); it != mapStudent.end(); it++){40 std::cout << it->second << std::endl;41 }42 }
转载于:https://www.cnblogs.com/chris-cp/p/5053380.html