Map是一个通过key(键)来获得value(值)的模板类。另一个问题是你希望在map中使用自己的类而不是已有的数据类型,比如现在已经用过的int。建立一个“为模板准备的(template-ready)”类,你必须确保在该类中包含一些成员函数和重载操作符。下面的一些成员是必须的:
•缺省的构造函数(通常为空)
•拷贝构造函数
•重载的”=”运算符
你应该重载尽可能多的运算符来满足特定模板的需要,比如,如果你想定义一个类作为 map中的键(key),你必须重载相关的运算符。但在这里不对重载运算符做过多讨论了。
//程序:映射自定义的类。
//目的:说明在map中怎样使用自定义的类。
#include <string>
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class CStudent
{
public:
int nStudentID;
int nAge;
public:
CStudent(){}//缺省构造函数——通常为空
//完整的构造函数
CStudent(int nSID, int nA){ nStudentID=nSID; nAge=nA;}
//拷贝构造函数
CStudent(const CStudent& ob){ nStudentID=ob.nStudentID; nAge=ob.nAge;}
// 重载“=”
void operator = (const CStudent& ob){nStudentID=ob.nStudentID; nAge=ob.nAge;}
};
int main(int argc, char* argv[])
{
map <string, CStudent> mapStudent;
mapStudent["Joe Lennon"] = CStudent(103547, 22);
mapStudent["Phil McCartney"] = CStudent(100723, 22);
mapStudent["Raoul Starr"] = CStudent(107350, 24);
mapStudent["Gordon Hamilton"] = CStudent(102330, 22);
// 通过姓名来访问Cstudent类中的成员
cout <<"The Student number for Joe Lennon is "<<
(mapStudent["Joe Lennon"].nStudentID) << endl;
return 0;
}