map中怎样使用自定义的类
文章来源:STL入门教程.chm
[cpp]
//程序:映射自定义的类
//目的:说明在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);
mapStudent[“C Plus Plus”] = mapStudent[“Joe Lennon”];
// 通过姓名来访问Cstudent类中的成员
cout<<“Joe Lennon Number is”<<(mapStudent[“Joe Lennon”].nStudentID)<<endl;
cout<<“CPlusPlus Number is”<<(mapStudent[“C Plus Plus”].nStudentID)<<endl;
return 0;
}
[/cpp]