stl之map 排序


  排序問題,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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM