STL hash_map初识

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值