STL(十六)hash_map哈希映照容器

        hash_map哈希映照容器与map映照容器比较相似,都将记录型的元素划分为键值和映照数据两个部分,然后根据键值的大小,将键值不重复的元素插入容器。不同之处在于,hash_map使用哈希表的数据结构,map使用红黑树的数据结构。对于元素的检索来说,这两种数据结构都有快速的检索效率。hash_map检索时使用的键值比较次数少,容器需占用较多的空间,用迭代器遍历出来的元素是非排序的。map则使用链表的二分法进行检索,空间使用率高,用迭代器遍历出来的元素是排序的,而且可提供反向迭代器。

一、hash_map技术原理


二、hash_map应用基础

#include <hash_map>

1、创建hash_map对象

      hash_map()

      hash_map(size_type  n)

      hash_map(size_type n, const  hasher  &h)

      hash_map(size_type n, const hasher &h, const  key_equal &k)

      hash_map(const  hash_set &)

2、元素插入

      pair<iterator,bool>  insert(const value_type &v)

      void insert(InputIterator  first, InputIterator last)

3、元素的删除

      void   erase(iterator  position)

      size_type  erase(const key_type  &k)

      void erase(iterator first, iterator last)

      void clear()

4、元素的遍历访问

      iterator  begin()

      iterator  end()

#include <iostream>
#include <hash_map>
template<class Key, class NameType, class YearType, class AddrType>
struct StudentRecord_tag { //学生记录结构体
    struct StudentInfo_tag { //学生信息结构体
        NameType  name;
        YearType  year;
        AddrType  addr;
    };
    //
    typedef Key IdType;
    typedef StudentInfo_tag  StudentInfo;
    //
    IdType  id;       //学号
    StudentInfo  sf;  //学生信息,
};
int main(void) {
    using namespace std;
    typedef StudentRecord_tag<int, char*, int, char*> StudentRecord;
    StudentRecord  srArray[] =  { //3笔学生记录
         {192, "李强", 21, "北京" },
         {193, "王文", 29, "上海" },
         {191, "张三", 38, "深圳" }
    };
    //
    hash_map<StudentRecord::IdType, StudentRecord::StudentInfo> hm;
    //
    for (int j=0; j<3; j++) {
        hm[srArray[j].id] = srArray[j].sf;
    }
    //迭代器遍历元素
    hash_map<StudentRecord::IdType, StudentRecord::StudentInfo>::iterator i, iend;
    iend = hm.end();
    cout << "学号   " << "姓名   " << "年龄   " << "地址   " << endl;
    for (i=hm.begin(); i!=iend; i++) {
        cout << (*i).first << ' '
             << (*i).second.name << '   '
             << (*i).second.year << '   '
             << (*i).second.addr << '   '
             << endl;
    }
    return 0;
}

5、元素的搜索

      iterator   find(const   key_type  &k)  const

6、其他的常用函数








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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值