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));
}