C++ hash_map的用法
#include <iostream>
#include <string>
#include <hash_map>
#include<string.h>
#include<stdio.h>
#include <ext/hash_map>
using namespace __gnu_cxx;
using namespace std;
class data{
public:
int iNumber;
char *pszName;
data()
{
pszName = new char(20);
}
~data()
{
delete []pszName;
}
int getNumber()
{
return iNumber;
}
void SetNumber(int Number)
{
iNumber = Number;
}
void GetName(char *pszNa)
{
strcpy(pszNa,pszName);
}
void SetName(char *pName)
{
strcpy(pszName,pName);
}
};
int main(void)
{
char name[20] = {0};
hash_map<int, data *> hm;
hm[1]->SetNumber(10);
printf("NUmber = %d\n",hm[1]->getNumber());
hm[1]->SetName("wangzheng");
hm[1]->GetName(name);
printf("Nmae = %s\n",name);
return 0;
}
上面的代码中
运行会出现段错误,原因是:hash_map<int, data *> hm;-----data* 没有分配空间
hash_map<int, data *> hm中data*必须用指针,如何给data*分配一个合法的空间?
求指点!
[解决办法]
pszName = new char(20);
改成:
pszName = new char[20];