hash_map and map

这里列几个常见问题,应该对你理解和使用hash_map比较有帮助。

4.1 hash_map和map的区别在哪里?

  • 构造函数。hash_map需要hash函数,等于函数;map只需要比较函数(小于函数).
  • 存储结构。hash_map采用hash表存储,map一般采用红黑树(RB Tree)实现。因此其memory数据结构是不一样的。

4.2 什么时候需要用hash_map,什么时候需要用map?

总 体来说,hash_map 查找速度会比map快,而且查找速度基本和数据量大小无关,属于常数级别;而map的查找速度是log(n)级别。并不一定常数就比log(n) 小,hash还有hash函数的耗时,明白了吧,如果你考虑效率,特别是在元素达到一定数量级时,考虑考虑hash_map。但若你对内存使用特别严格,希望程序尽可能少消耗内存,那么一定要小心,hash_map可能会让你陷入尴尬,特别是当你的hash_map对象特别多时,你就更无法控制了,而且 hash_map的构造速度较慢。

现在知道如何选择了吗?权衡三个因素: 查找速度, 数据量, 内存使用。

这里还有个关于hash_map和map的小故事,看看:http://dev.csdn.net/Develop/article/14/14019.shtm

4.3 如何在hash_map中加入自己定义的类型?

你只要做两件事, 定义hash函数,定义等于比较函数。下面的代码是一个例子:

#include <hash_map>

#include <string>

#include <iostream>

 

using namespace std;

//define the class

class ClassA{

        public:

        ClassA(int a):c_a(a){}

        int getvalue()const { return c_a;}

        void setvalue(int a){c_a=a;}

        private:

        int c_a;

};

 

//1 define the hash function

struct hash_A{

        size_t operator()(const class ClassA & A)const{

                //  return  hash<int>(classA.getvalue());

                return A.getvalue();

        }

};

 

//2 define the equal function

struct equal_A{

        bool operator()(const class ClassA & a1, const class ClassA & a2)const{

                return  a1.getvalue() == a2.getvalue();

        }

};

 

int main()

{

        hash_map<ClassA, string, hash_A, equal_A> hmap;

        ClassA a1(12);

        hmap[a1]="I am 12";

        ClassA a2(198877);

        hmap[a2]="I am 198877";

       

        cout<<hmap[a1]<<endl;

        cout<<hmap[a2]<<endl;

        return 0;

}


 

I am 12

I am 198877

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值