hash_map 查找速度会比map快,而且查找速度基本和数据量大小无关,属于常数级别;
而map的查找速度是log(n)级别。如果你考虑效率,特别是在元素达到一定数量级时,考虑考虑hash_map。
但若你对内存使用特别严格,希望程序尽可能少消耗内存,那么一定要小心,hash_map可能会让你陷入尴尬,特别是当你的hash_map对象特别多时,你就更无法控制了,而且hash_map的构造速度较慢。
用法:
当string作为key时,hash_map()需要重载重载operator();
struct compare_str
{
bool operator()(const char* p1, const char*p2) const
{
return strcmp(p1,p2)==0;
}
};
然后value可以是任意的,这里用了结构体指针。
#include <hash_map>
#include <string>
#include <cstring>
#include <iostream>
#include <malloc.h>
using namespace std;
using namespace __gnu_cxx;
struct tcp
{
int id;
int time;
};
typedef struct tcp tcpNode;
struct compare_str
{
bool operator()(const char* p1, const char*p2) const
{
return strcmp(p1,p2)==0;
}
};
int main()
{
typedef hash_map<const char*, tcpNode *, hash<const char*>, compare_str> StrIntMap;
StrIntMap tcphash;
tcpNode * newnode = (tcpNode *)malloc(sizeof(tcpNode));
newnode->id=11;
newnode->time=22;
tcphash["zhangsan"]=newnode;
cout<<tcphash["zhangsan"]->id;
}