最近在使用unordered_map临时存储数据时候,总是出现程序异常退出的情况,调试查找了好久才找到原因,特意写了一个小demo记录一下。
使用char* 作为key,需要重载相应的比较函数和hash函数,原因是:使用本身的比较函数,他比较的仅仅是两个指针的地址,而不是两个指针存放的地址,因此需要重载strcmp函数进行判断。hash也是,使用指针地址座位key进行hash的而不是指针存放的地址进行,所以需要传入一个字符串查找。
#include<unordered_map>
#include <iostream>
#include <string.h>
using namespace std;
struct char_cmp
{
bool operator()( const char* a, const char* b)const
{
return strcmp(a, b) == 0;
}
};
struct Hash_map
{
int operator()(const char* str)const
{
int seed = 131;
int hash = 0;
while(*str)
{
hash = (hash * seed) + (*str);
str ++;
}
return hash & (0x7FFFFFFF);
}
};
struct TestData
{
TestData()
{
memset(this,0,sizeof(*this));
}
char m_cData[20];
int m_i;
};
typedef unordered_map<const char*,TestData*,Hash_map,char_cmp> TestMapT;
TestMapT m