stl hash_map 详细说明

来源:互联网 发布:linux 同步时区命令 编辑:程序博客网 时间:2024/05/18 01:51

hash_map是stl的非标准(拓展)的里的存储结构。

本文目录:

1 、hash_map原理

2 、hash_map 使用

2.1 一个简单实例

2.2 hash_map 的hash函数对象

2.3 hash_map 的比较函数对象

3、hash_map和map

3.1 hash_map和map的区别在哪里

3.2 什么时候需要用hash_map,什么时候需要用map

4、项目使用实例

本文内容:

1 、hash_map原理

hash_map基于hash table(哈希表)。 哈希表最大的优点,就是把数据的存储和查找消耗的时间大大降低,几乎可以看成是常数时间(需要一个较好的哈希函数);而代价仅仅是消耗比较多的内存。然而在当前可利用内存越来越多的情况下,用空间换时间的做法是值得的。尤其是在key从1开始(为整形)均匀递增的情况下,hashmap 的存储和查找的时间最短,空间利用率也较小。

其基本原理是:使用一个下标范围比较大的数组来存储元素。可以设计一个函数(哈希函数,也叫做散列函数),使得每个元素的关键字都与一个函数值(即数组下标,hash值)相对应,于是用这个数组单元来存储这个元素;也可以简单的理解为,按照关键字为每一个元素“分类”,然后将这个元素存储在相应“类”所对应的地方,称为桶。

但是,不能够保证每个元素的关键字与函数值是一一对应的,因此极有可能出现对于不同的元素,却计算出了相同的函数值,这样就产生了“冲突”,换句话说,就是把不同的元素分在了相同的“类”之中。 总的来说,“直接定址”与“解决冲突”是哈希表的两大特点。

hash_map,首先分配一大片内存,形成许多桶。是利用hash函数,对key进行映射到不同区域(桶)进行保存。其插入过程是:

  1. 得到key
  2. 通过hash函数得到hash值
  3. 得到桶号(一般都为hash值对桶数求模)
  4. 存放value在桶内。
其取值过程是:
  1. 得到key
  2. 通过hash函数得到hash值
  3. 得到桶号(一般都为hash值对桶数求模)
  4. 比较桶的内部元素是否与key相等,若都不相等,则没有找到。
  5. 取出相等的记录的value。
hash_map中直接地址用hash函数生成,解决冲突,用比较函数解决。这里可以看出,如果每个桶内部只有一个元素,那么查找的时候只有一次比较。当许多桶内没有值时,许多查询就会更快了(指查不到的时候).

由此可见,要实现哈希表, 和用户相关的是:hash函数和比较函数。这两个参数刚好是我们在使用hash_map时需要指定的参数。

2 、hash_map 使用

2.1 一个简单实例

我们先看一个简单的例子:随机给你一个ID号和ID号相应的信息,ID号的范围是1~2的31次方。如何快速保存查找。

#include <hash_map>#include <string>usingnamespace std;int main(){        hash_map<int, string> mymap;        mymap[9527]="唐伯虎点秋香";        mymap[1000000]="百万富翁的生活";        mymap[10000]="白领的工资底线";        ...        if(mymap.find(10000) != mymap.end()){                ...        }

如果没有指定hash函数对象和比较函数对象,那么stl会替你指定默认的hash函数对象和比较函数对象。

SGI STL里的hash_map的前置声明和实现。

// Forward declaration of equality operator; needed for friend  // declaration.  template<class _Key, class _Tp,   class _HashFcn = hash<_Key>,   class _EqualKey = equal_to<_Key>,   class _Alloc = allocator<_Tp> >    class hash_map;  /**   *  This is an SGI extension.   *  @ingroup SGIextensions   *  @doctodo   */  template <class _Key, class _Tp, class _HashFcn, class _EqualKey,    class _Alloc>    class hash_map    {...};


也就是hash_map<int, string> mymap;//等同于:hash_map<int, string, hash<int>, equal_to<int> > mymap;
对于Alloc,需要了解的人可百度 标准库 STL :Allocator能做什么 。  

2.2 hash_map 的hash函数对象

SGI STL提供一系列针对原子类型的的默认哈希函数。

hash< int>源码:

struct hash<int> {        size_t operator()(int __x) const { return __x; }};
原来是个函数对象。在SGI STL中,提供了以下hash函数:
struct hash<char*>struct hash<constchar*>struct hash<char> struct hash<unsignedchar> struct hash<signedchar>struct hash<short>struct hash<unsignedshort> struct hash<int> struct hash<unsignedint>struct hash<long> struct hash<unsignedlong> 
对于自定义的类型必须自定义hash函数对象。例如:
struct str_hash{        size_t operator()(const string& str) const        {                unsignedlong __h = 0;                for (size_t i = 0 ; i < str.size() ; i ++)                __h = 5*__h + str[i];                return size_t(__h);        }};//如果你希望利用系统定义的字符串hash函数,你可以这样写:
struct str_hash{        size_t operator()(const string& str) const        {                returnreturn __stl_hash_string(str.c_str());        }};
在声明自己的哈希函数时要注意以下几点:
  1. 使用struct,然后重载operator().
  2. 返回是size_t
  3. 参数是你要hash的key的类型。
  4. 函数是const类型的。
如果这些比较难记,最简单的方法就是照猫画虎,找一个函数改改就是了。

map转到hash_map只需要把

typedef map<string, string> namemap; 改成 typedef hash_map<string, string, str_hash> namemap;

2.3 hash_map 的比较函数对象

在map中的比较函数,需要提供less函数。如果没有提供,缺省的也是less< Key> 。在hash_map中,要比较桶内的数据和key是否相等,因此需要的是是否等于的函数:equal_to< Key> 。先看看equal_to的源码:
//本代码可以从SGI STL//先看看binary_function 函数声明,其实只是定义一些类型而已。template <class _Arg1, class _Arg2, class _Result>struct binary_function {        typedef _Arg1 first_argument_type;        typedef _Arg2 second_argument_type;        typedef _Result result_type;};//看看equal_to的定义:template <class _Tp>struct equal_to : public binary_function<_Tp,_Tp,bool>{        bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; }};

如果你使用一个自定义的数据类型,如struct mystruct, 或者const char* 的字符串,如何使用比较函数?使用比较函数,有两种方法. 第一种是:重载==操作符,利用equal_to;看看下面的例子:
struct mystruct{        int iID;        int  len;        bool operator==(const mystruct & my) const{                return (iID==my.iID) && (len==my.len) ;        }};  
这样,就可以使用equal_to< mystruct>作为比较函数了。另一种方法就是使用函数对象。自定义一个比较函数体:
struct compare_str{        bool operator()(constchar* p1, constchar*p2) const{                return strcmp(p1,p2)==0;        }};  
有了compare_str,就可以使用hash_map了。
typedef hash_map<constchar*, string, hash<constchar*>, compare_str> StrIntMap;StrIntMap namemap;namemap["1"]="1111";namemap["2"]="2222";namemap["3"]="3333";

3、hash_map和map

3.1 hash_map和map的区别在哪里

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

3.2 什么时候需要用hash_map,什么时候需要用map

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

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

4、项目使用实例

在具体的项目中只用需要进行一定的封装。以下是以游戏服务器的角色管理器为例。

哈希map的定义为    typedef __gnu_cxx::hash_map<Key, Value,hash_func,key_equal > hashmap;
hash函数对象为    struct hash_func : public std::unary_function<const Key, size_t> (支持字符串类型和无符号整形)
比较函数对象为   struct key_equal : public std::binary_function<Key, Key, bool> (支持字符串类型和无符号整形)(也可以使用重载等号操作符来实现)
hashmap_string_uint32 作为hashmap的管理者,是实现了支持string和uint32的作为索引的hashmap封装类。
 
/**
 * \description 有限桶Hash管理模板,非线程安全
 *
 * 目前支持两种key类型(uint32 , string),value类型不作限制,但此类型要可copy的。
 * \param Key key类型(uint32 , string)
 * \param Value value类型
 */
template <class Key,class Value>
class hashmap_string_uint32 : private noncopyable//支持
{
    private:
        struct hash_func : public std::unary_function<const Key, size_t> //哈希仿函数(针对字符串类型和无符号整形的,重载括号运算符)
    {    
        size_t operator()(const std::string &s) const{ return __gnu_cxx::hash<const char*>()( s.c_str() );}


        size_t operator()(const uint32 & k) const{ return k; }  
    };
        /**
         * \description key值等值比较,目前支持 (uint32 , char *),两种类型
         */
        struct key_equal : public std::binary_function<Key, Key, bool>//比较函数对象
    {
        /**
         * \description 字串的等值比较
         *
         *
         * \param s1 比较参数1
         * \param s2 比较参数2
         * \return 是否相等
         */
        bool operator()(const std::string &s1, const std::string& s2) const
        {
            return strcmp(s1.c_str(), s2.c_str()) == 0;
        }
        /**
         * \description 数值的等值比较
         *
         *
         * \param s1 比较参数1
         * \param s2 比较参数2
         * \return 是否相等
         */
        bool operator()(const uint32 s1, const uint32 s2) const
        {
            return s1 == s2;
        }
    };

    public:
        /**
         * \description hash_map容器
         */
        typedef __gnu_cxx::hash_map<Key, Value,hash_func,key_equal > hashmap;
        /**
         * \description 迭代
         *
         */
        typedef typename hashmap::iterator hashmap_iter;
        /**
         * \description 迭代
         *
         */
        typedef typename hashmap::const_iterator const_iter;
    protected:
        /**
         * \description hash_map容器
         */
        hashmap ets;


        /**
         * \description 插入数据,如果原来存在相同key值的数据,原来数据将会被替换
         * \param key key值
         * \param value 要插入的数据
         * \return 成功返回true,否则返回false
         */
        bool insert(const Key &key,Value &value)
        {
            ets[key]=value;
            return true;
        }


        /**
         * \description 根据key值查找并得到数据
         * \param key 要寻找的key值
         * \param value 返回结果将放入此处,未找到将不会改变此值
         * \return 查找到返回true,未找到返回false
         */
        bool find(const Key &key,Value &value) const
        {
            const_iter it = ets.find(key);
            if(it != ets.end())
            {
                value = it->second;
                return true;
            }
            else
                return false;
        }

        /**
         * \description 构造函数
         *
         */
        hashmap_string_uint32()
        {
        }

        /**
         * \description 析构函数,清除所有数据
         */
        ~hashmap_string_uint32()
        {
            clear();
        }
        /**
         * \description 移除数据
         * \param key 要移除的key值
         */
        void remove(const Key &key)
        {
            ets.erase(key);
        }

        /**
         * \description 清除所有数据
         */
        void clear()
        {
            ets.clear();
        }

        /**
         * \description 统计数据个数
         */
        size_t size() const
        {
            return ets.size();
        }

        /**
         * \description 判断容器是否为空
         */
        bool empty() const
        {
            return ets.empty();
        }
};


比如角色管理器:
角色管理器继承了hashmap_string_uint32<uint32,T *>,键是角色guid,值是角色指针。
角色管理器, 实现了ID、名字的索引,所以这些值不能重复。

template <typename T,bool lock=true>
class player_manager:public base_manager<index_uint32, index_string>,  public bool_rwlock<lock>
{
...
};
其中:
以ID为key值的指针容器,需要继承使用

class index_uint32:public hashmap_string_uint32<uint32,base_object *>

以名字为key值的指针容器,需要继承使用
class index_string:public hashmap_string_uint32<std::string, base_object *>
base_manager 是支持多索引的管理器
template<typename e1,typename e2=index_null<2>, typename e3=index_null<3>  , bool need_list = true>
class base_manager :protected e1,protected e2,protected e3

这样角色管理器就可以根据角色id和角色名称来查找角色指针了。


ps:
这里针对string使用的是stl里的默认的字符串函数 __gnu_cxx::hash<const char*> 来确定哈希值。
其他特殊字符串类型需要自定义的。可参考:http://blog.csdn.net/sdhongjun/article/details/4517325



0 0
原创粉丝点击