STL(十六)hash

xiaoxiao2021-02-28  95

        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、其他的常用函数

转载请注明原文地址: https://www.6miu.com/read-94922.html

最新回复(0)