Map是STL的一個關聯容器,它提供一對一(其中第一個能夠稱爲關鍵字,每一個關鍵字只能在map中出現一次,第二個可能稱爲該關鍵字的值)的數據處理能力,因爲這個特性,它完成有可能在咱們處理一對一數據的時候,在編程上提供快速通道。這裏說下map內部數據的組織,map內部自建一顆紅黑樹(一種非嚴格意義上的平衡二叉樹),這顆樹具備對數據自動排序的功能,因此在map內部全部的數據都是有序的,後邊咱們會見識到有序的好處。
ios
在一些特殊狀況,好比關鍵字是一個結構體,涉及到排序就會出現問題,由於它沒有小於號操做,insert等函數在編譯的時候過不去,下面給出兩個方法解決這個問題web
第一種:小於號重載,程序舉例編程
#include <map>數組
#include <string>ide
Using namespace std;函數
Typedef struct tagStudentInfospa
{orm
Int nID;排序
String strName;three
}StudentInfo, *PStudentInfo; //學生信息
Int main()
{
int nSize;
//用學生信息映射分數
map<StudentInfo, int>mapStudent;
map<StudentInfo, int>::iterator iter;
StudentInfo studentInfo;
studentInfo.nID = 1;
studentInfo.strName = 「student_one」;
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));
studentInfo.nID = 2;
studentInfo.strName = 「student_two」;
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));
for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)
cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl;
}
以上程序是沒法編譯經過的,只要重載小於號,就OK了,以下:
Typedef struct tagStudentInfo
{
Int nID;
String strName;
Bool operator < (tagStudentInfo const& _A) const
{
//這個函數指定排序策略,按nID排序,若是nID相等的話,按strName排序
If(nID < _A.nID) return true;
If(nID == _A.nID) return strName.compare(_A.strName) < 0;
Return false;
}
}StudentInfo, *PStudentInfo; //學生信息
第二種:仿函數的應用,這個時候結構體中沒有直接的小於號重載,程序說明
#include <map>
#include <string>
Using namespace std;
Typedef struct tagStudentInfo
{
Int nID;
String strName;
}StudentInfo, *PStudentInfo; //學生信息
Classs sort
{
Public:
Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const
{
If(_A.nID < _B.nID) return true;
If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;
Return false;
}
};
Int main()
{
//用學生信息映射分數
Map<StudentInfo, int, sort>mapStudent;
StudentInfo studentInfo;
studentInfo.nID = 1;
studentInfo.strName = 「student_one」;
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));
studentInfo.nID = 2;
studentInfo.strName = 「student_two」;
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));
}