哈希表入门讲解

来源:互联网 发布:java中flag的用法 编辑:程序博客网 时间:2024/06/05 04:33

散列表Hash table,也叫哈希表),是根据键(Key)而直接访问在内存存储位置的数据结构。也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。这个映射函数称做散列函数,存放记录的数组称做散列表

一个通俗的例子是,为了查找电话簿中某人的号码,可以创建一个按照人名首字母顺序排列的表(即建立人名{\displaystyle x}x到首字母{\displaystyle F(x)}F(x)的一个函数关系),在首字母为W的表中查找“王”姓的电话号码,显然比直接查找就要快得多。这里使用人名作为关键字,“取首字母”是这个例子中散列函数的函数法则{\displaystyle F()}F(),存放首字母的表对应散列表。关键字和函数法则理论上可以任意确定。

基本概念

  • 若关键字为{\displaystyle k}k,则其值存放在{\displaystyle f(k)}f(k)的存储位置上。由此,不需比较便可直接取得所查记录。称这个对应关系{\displaystyle f}f为散列函数,按这个思想建立的表为散列表。
  • 对不同的关键字可能得到同一散列地址,即{\displaystyle k_{1}\neq k_{2}}k_{1}\neq k_{2},而{\displaystyle f(k_{1})=f(k_{2})}f(k_{1})=f(k_{2}),这种现象称为冲突英语:Collision)。具有相同函数值的关键字对该散列函数来说称做同义词。综上所述,根据散列函数{\displaystyle f(k)}f(k)和处理冲突的方法将一组关键字映射到一个有限的连续的地址集(区间)上,并以关键字在地址集中的“像”作为记录在表中的存储位置,这种表便称为散列表,这一映射过程称为散列造表或散列,所得的存储位置称散列地址。
  • 若对于关键字集合中的任一个关键字,经散列函数映象到地址集合中任何一个地址的概率是相等的,则称此类散列函数为均匀散列函数(Uniform Hash function),这就是使关键字经过散列函数得到一个“随机的地址”,从而减少冲突。

构造散列函数

散列函数能使对一个数据序列的访问过程更加迅速有效,通过散列函数,数据元素将被更快定位。

  1. 直接定址法:取关键字或关键字的某个线性函数值为散列地址。即{\displaystyle hash(k)=k}hash(k)=k{\displaystyle hash(k)=a\cdot k+b}hash(k)=a\cdot k+b,其中{\displaystyle a\,b}a\,b为常数(这种散列函数叫做自身函数)
  2. 数字分析法:假设关键字是以r为基的数,并且哈希表中可能出现的关键字都是事先知道的,则可取关键字的若干数位组成哈希地址。
  3. 平方取中法:取关键字平方后的中间几位为哈希地址。通常在选定哈希函数时不一定能知道关键字的全部情况,取其中的哪几位也不一定合适,而一个数平方后的中间几位数和数的每一位都相关,由此使随机分布的关键字得到的哈希地址也是随机的。取的位数由表长决定。
  4. 折叠法:将关键字分割成位数相同的几部分(最后一部分的位数可以不同),然后取这几部分的叠加和(舍去进位)作为哈希地址。
  5. 随机数法
  6. 除留余数法:取关键字被某个不大于散列表表长m的数p除后所得的余数为散列地址。即{\displaystyle hash(k)=k\,{\bmod {\,}}p}hash(k)=k\,{\bmod  \,}p{\displaystyle p\leq m}p\leq m。不仅可以对关键字直接取模,也可在折叠法、平方取中法等运算之后取模。对p的选择很重要,一般取素数或m,若p选择不好,容易产生冲突。

处理冲突

为了知道冲突产生的相同散列函数地址所对应的关键字,必须选用另外的散列函数,或者对冲突结果进行处理。而不发生冲突的可能性是非常之小的,所以通常对冲突进行处理。常用方法有以下几种:

  • 开放定址法(open addressing):{\displaystyle hash_{i}=(hash(key)+d_{i})\,{\bmod {\,}}m}hash_{i}=(hash(key)+d_{i})\,{\bmod  \,}m{\displaystyle i=1,2...k\,(k\leq m-1)}i=1,2...k\,(k\leq m-1),其中{\displaystyle hash(key)}hash(key)为散列函数,{\displaystyle m}m为散列表长,{\displaystyle d_{i}}d_{i}为增量序列,{\displaystyle i}i为已发生冲突的次数。增量序列可有下列取法:
{\displaystyle d_{i}=1,2,3...(m-1)}d_{i}=1,2,3...(m-1)称为 线性探测(Linear Probing);即{\displaystyle d_{i}=i}d_{i}=i,或者为其他线性函数。相当于逐个探测存放地址的表,直到查找到一个空单元,把散列地址存放在该空单元。
{\displaystyle d_{i}=\pm 1^{2},\pm 2^{2},\pm 3^{2}...\pm k^{2}}d_{i}=\pm 1^{2},\pm 2^{2},\pm 3^{2}...\pm k^{2} {\displaystyle (k\leq m/2)}(k\leq m/2)称为 平方探测(Quadratic Probing)。相对线性探测,相当于发生冲突时探测间隔{\displaystyle d_{i}=i^{2}}d_{i}=i^{2}个单元的位置是否为空,如果为空,将地址存放进去。
{\displaystyle d_{i}=}d_{i}=伪随机数序列,称为 伪随机探测

显示线性探测填装一个散列表的过程:

关键字为{89,18,49,58,69}插入到一个散列表中的情况。此时线性探测的方法是取{\displaystyle d_{i}=i}d_{i}=i。并假定取关键字除以10的余数为散列函数法则。
散列地址空表插入89插入18插入49插入58插入690


4949491



58582




693





4





5





6





7





8

181818189
8989898989
第一次冲突发生在填装49的时候。地址为9的单元已经填装了89这个关键字,所以取{\displaystyle i=1}i=1,往下查找一个单位,发现为空,所以将49填装在地址为0的空单元。第二次冲突则发生在58上,取{\displaystyle i=2}i=2,往下查找两个单位,将58填装在地址为1的空单元。69同理。
表的大小选取至关重要,此处选取10作为大小,发生冲突的几率就比选择质数11作为大小的可能性大。越是质数,mod取余就越可能均匀分布在表的各处。

聚集(Cluster,也翻译做“堆积”)的意思是,在函数地址的表中,散列函数的结果不均匀地占据表的单元,形成区块,造成线性探测产生一次聚集(primary clustering)和平方探测的二次聚集(secondary clustering),散列到区块中的任何关键字需要查找多次试选单元才能插入表中,解决冲突,造成时间浪费。对于开放定址法,聚集会造成性能的灾难性损失,是必须避免的。

  • 单独链表法:将散列到同一个存储位置的所有元素保存在一个链表中。实现时,一种策略是散列表同一位置的所有冲突结果都是用栈存放的,新元素被插入到表的前端还是后端完全取决于怎样方便。
  • 双散列。
  • 再散列:{\displaystyle hash_{i}=hash_{i}(key)}hash_{i}=hash_{i}(key){\displaystyle i=1,2...k}i=1,2...k{\displaystyle hash_{i}}hash_{i}是一些散列函数。即在上次散列计算发生冲突时,利用该次冲突的散列函数地址产生新的散列函数地址,直到冲突不再发生。这种方法不易产生“聚集”(Cluster),但增加了计算时间。
  • 建立一个公共溢出区

例程

在C语言中,实现以上过程的简要程序[1]

开放定址法:HashTableInitializeTable( int TableSize ){    HashTable H;    int i;    /* 为散列表分配空间。 */    /* 有些编译器不支持为 struct HashTable 分配空间,声称这是一个不完全的结构, */    /* 可使用一个指向 HashTable 的指针为之分配空间。 */    /* 如:sizeof( Probe ),Probe 作为 HashTable 在 typedef 定义的指针。 */    H = malloc( sizeof( struct HashTable ) );    /* 散列表大小为一个质数。 */    H->TableSize = Prime;    /* 分配表所有地址的空间。 */    H->Cells = malloc( sizeof( Cell )  * H->TableSize );    /* 地址初始为空。 */    for( i = 0; i < H->TableSize; i++ )        H->Cells[i].info = Empty;    return H;}

查找空单元并插入:PositionFind( ElementType Key, HashTable H ){    Position Current;    int CollisionNum;    /* 冲突次数初始为0。 */    /* 通过表的大小对关键字进行处理。 */    CollisionNum = 0;    Current = Hash( Key, H->TableSize );    /* 不为空时进行查找。 */    while( H->Cells[Current].info != Empty &&        H->Cells[Current].Element != Key )    {        Current = ++CollosionNum * ++CollisionNum;        /* 向下查找超过表范围时回到表开头。 */        if( Current >= H->TableSize )            Current -= H->TableSize;    }    return Current;}

查找效率

散列表的查找过程基本上和造表过程相同。一些关键码可通过散列函数转换的地址直接找到,另一些关键码在散列函数得到的地址上产生了冲突,需要按处理冲突的方法进行查找。在介绍的三种处理冲突的方法中,产生冲突后的查找仍然是给定值与关键码进行比较的过程。所以,对散列表查找效率的量度,依然用平均查找长度来衡量。

查找过程中,关键码的比较次数,取决于产生冲突的多少,产生的冲突少,查找效率就高,产生的冲突多,查找效率就低。因此,影响产生冲突多少的因素,也就是影响查找效率的因素。影响产生冲突多少有以下三个因素:

  1. 散列函数是否均匀;
  2. 处理冲突的方法;
  3. 散列表的载荷因子(英语:load factor)。

载荷因子

散列表的载荷因子定义为:{\displaystyle \alpha }\alpha  = 填入表中的元素个数 / 散列表的长度

{\displaystyle \alpha }\alpha 是散列表装满程度的标志因子。由于表长是定值,{\displaystyle \alpha }\alpha 与“填入表中的元素个数”成正比,所以,{\displaystyle \alpha }\alpha 越大,表明填入表中的元素越多,产生冲突的可能性就越大;反之,{\displaystyle \alpha }\alpha 越小,标明填入表中的元素越少,产生冲突的可能性就越小。实际上,散列表的平均查找长度是载荷因子{\displaystyle \alpha }\alpha 的函数,只是不同处理冲突的方法有不同的函数。

对于开放定址法,荷载因子是特别重要因素,应严格限制在0.7-0.8以下。超过0.8,查表时的CPU缓存不命中(cache missing)按照指数曲线上升。因此,一些采用开放定址法的hash库,如Java的系统库限制了荷载因子为0.75,超过此值将resize散列表。

举例:Linux内核的bcache[编辑]

Linux操作系统在物理文件系统与块设备驱动程序之间引入了“缓冲区缓存”(Buffer Cache,简称bcache)。当读写磁盘文件的数据,实际上都是对bcache操作,这大大提高了读写数据的速度。如果要读写的磁盘数据不在bcache中,即缓存不命中(miss),则把相应数据从磁盘加载到bcache中。一个缓存数据大小是与文件系统上一个逻辑块的大小相对应的(例如1KiB字节),在bcache中每个缓存数据块用struct buffer_head记载其元信息:

struct buffer_head {                 char * b_data;    //指向缓存的数据块的指针                    unsigned long b_blocknr;   //逻辑块号                 unsigned short b_dev;         //设备号                 unsigned char b_uptodate;  //缓存中的数据是否是最新的                 unsigned char b_dirt;           //缓存中数据是否为脏数据                 unsigned char b_count;        //这个缓存块被引用的次数                 unsigned char b_lock;          //b_lock表示这个缓存块是否被加锁                 struct task_struct * b_wait;   //等待在这个缓存块上的进程                 struct buffer_head * b_prev;  //指向缓存中相同hash值的下一个缓存块                 struct buffer_head * b_next; //指向缓存中相同hash值的上一个缓存块                 struct buffer_head * b_prev_free; //缓存块空闲链表中指向下一个缓存块                 struct buffer_head * b_next_free;  //缓存块空闲链表中指向上一个缓存块};

C++ STL中,哈希表对应的容器是unordered_map(since C++ 11)。
根据C++ 11标准的推荐,用unordered_map代替hash_map

Prolouge

先来回顾一下数据结构中哈希表相关的知识。
哈希表是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度,这个映射函数叫做散列函数。
哈希表的一个重要问题就是如何解决映射冲突的问题。常用的有两种:开放地址法 和 链地址法

与map的区别

STL中,map对应的数据结构是红黑树。红黑树是一种近似于平衡的二叉查找树,里面的数据是有序的。在红黑树上做查找操作的时间复杂度为 O(logN)。而unordered_map对应 哈希表,哈希表的特点就是查找效率高,时间复杂度为常数级别 O(1), 而额外空间复杂度则要高出许多。所以对于需要高效率查询的情况,使用unordered_map容器。而如果对内存大小比较敏感或者数据存储要求有序的话,则可以用map容器。

基本使用

unordered_map的用法和map大同小异,一个简单示例:

#include <iostream>#include <unordered_map>#include <string>int main(int argc, char **argv) {    std::unordered_map<int, std::string> map;    map.insert(std::make_pair(1, "Scala"));    map.insert(std::make_pair(2, "Haskell"));    map.insert(std::make_pair(3, "C++"));    map.insert(std::make_pair(6, "Java"));    map.insert(std::make_pair(14, "Erlang"));    std::unordered_map<int, std::string>::iterator it;    if ((it = map.find(6)) != map.end()) {        std::cout << it->second << std::endl;    }    return 0;}

使用自定义类

要使用哈希表,必须要有对应的计算散列值的算法以及判断两个值(或对象)是否相等的方法。
在Java中,Object类里有两个重要方法:hashCodeequals方法。其中hashCode方法便是为散列存储结构服务的,用来计算散列值;而equals方法则是用来判断两对象是否等价。由于所有的类都继承自java.lang.Object类,因此所有类相当于都拥有了这两个方法。

而在C++中没有自动声明这类函数,STL只为C++常用类提供了散列函数,因此如果想在unordered_map中使用自定义的类,则必须为此类提供一个哈希函数和一个判断对象是否相等的函数(e.g. 重载==运算符)。下面是一个简单示例(扒自数据结构上机作业的部分代码):

using std::string;using std::cin;using std::cout;using std::endl;using std::unordered_map;class Person {//private://    string phone;//    string name;public:    string phone;    string name;    string address;    explicit Person() {}    explicit Person(string name, string phone, string address): name(name), phone(phone), address(address) {}    // overload operator==    bool operator==(const Person& p) {        return this->phone == p.phone && this->name == p.name            && this->address == p.address;    }    inline friend std::ostream& operator<<(std::ostream& os, Person& p) {        os << "[Person] -> (" << p.name << ", " << p.phone << ", "           << p.address << ")";        return os;    }};// declare hash<Person>namespace std { template <> struct hash<Person> {     std::size_t operator()(const Person& p) const {      using std::size_t;      using std::hash;      using std::string;      // Compute individual hash values for first,      // second and third and combine them using XOR      // and bit shifting:      return ((hash<string>()(p.phone)        ^ (hash<string>()(p.name) << 1)) >> 1)        ^ (hash<string>()(p.address) << 1);     } };}unordered_map<string, Person> phoneMap;void selectByPhone() {    string phone;    cout << "Input the phone number: "; cin >> phone;    unordered_map<string, Person>::iterator it;    int size = phoneMap.size();    for(int pc = 0; pc < size; pc++) {        if((it = phoneMap.find(phone)) != phoneMap.end()) {            cout << "\033[32mQuery result: " << it->second << "\033[0m" << endl;            return;        }    }    cout << "\033[33mQuery result : target_not_found\033[0m" << endl;}

0 为什么需要hash_map

用过map吧?map提供一个很常用的功能,那就是提供key-value的存储和查找功能。例如,我要记录一个人名和相应的存储,而且随时增加,要快速查找和修改:

岳不群-华山派掌门人,人称君子剑 张三丰-武当掌门人,太极拳创始人 东方不败-第一高手,葵花宝典 ...

这些信息如果保存下来并不复杂,但是找起来比较麻烦。例如我要找"张三丰"的信息,最傻的方法就是取得所有的记录,然后按照名字一个一个比较。如果要速度快,就需要把这些记录按照字母顺序排列,然后按照二分法查找。但是增加记录的时候同时需要保持记录有序,因此需要插入排序。考虑到效率,这就需要用到二叉树。讲下去会没完没了,如果你使用STL 的map容器,你可以非常方便的实现这个功能,而不用关心其细节。关于map的数据结构细节,感兴趣的朋友可以参看学习STL map, STL set之数据结构基础。看看map的实现:

#include <map> #include <string> using namespace std; ... map<string, string> namemap;//增加。。。namemap["岳不群"]="华山派掌门人,人称君子剑";namemap["张三丰"]="武当掌门人,太极拳创始人";namemap["东方不败"]="第一高手,葵花宝典";...//查找。。if(namemap.find("岳不群") != namemap.end()){...}

不觉得用起来很easy吗?而且效率很高,100万条记录,最多也只要20次的string.compare的比较,就能找到你要找的记录;200万条记录事,也只要用21次的比较。

速度永远都满足不了现实的需求。如果有100万条记录,我需要频繁进行搜索时,20次比较也会成为瓶颈,要是能降到一次或者两次比较是否有可能?而且当记录数到200万的时候也是一次或者两次的比较,是否有可能?而且还需要和map一样的方便使用。

答案是肯定的。这时你需要has_map. 虽然hash_map目前并没有纳入C++ 标准模板库中,但几乎每个版本的STL都提供了相应的实现。而且应用十分广泛。在正式使用hash_map之前,先看看hash_map的原理。

1 数据结构:hash_map原理

这是一节让你深入理解hash_map的介绍,如果你只是想囫囵吞枣,不想理解其原理,你倒是可以略过这一节,但我还是建议你看看,多了解一些没有坏处。

hash_map基于hash table(哈希表)。哈希表最大的优点,就是把数据的存储和查找消耗的时间大大降低,几乎可以看成是常数时间;而代价仅仅是消耗比较多的内存。然而在当前可利用内存越来越多的情况下,用空间换时间的做法是值得的。另外,编码比较容易也是它的特点之一。

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

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

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

  1. 得到key
  2. 通过hash函数得到hash值
  3. 得到桶号(一般都为hash值对桶数求模)
  4. 存放key和value在桶内。

其取值过程是:

  1. 得到key
  2. 通过hash函数得到hash值
  3. 得到桶号(一般都为hash值对桶数求模)
  4. 比较桶的内部元素是否与key相等,若都不相等,则没有找到。
  5. 取出相等的记录的value。

hash_map中直接地址用hash函数生成,解决冲突,用比较函数解决。这里可以看出,如果每个桶内部只有一个元素,那么查找的时候只有一次比较。当许多桶内没有值时,许多查询就会更快了(指查不到的时候).

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

2 hash_map 使用

2.1 一个简单实例

不要着急如何把"岳不群"用hash_map表示,我们先看一个简单的例子:随机给你一个ID号和ID号相应的信息,ID号的范围是1~2的31次方。如何快速保存查找。

#include <hash_map> #include <string> using namespace std; int main(){hash_map<int, string> mymap;mymap[9527]="唐伯虎点秋香";mymap[1000000]="百万富翁的生活";mymap[10000]="白领的工资底线";...if(mymap.find(10000) != mymap.end()){...}
够简单,和map使用方法一样。这时你或许会问?hash函数和比较函数呢?不是要指定么?你说对了,但是在你没有指定hash函数和比较函数的时候,你会有一个缺省的函数,看看hash_map的声明,你会更加明白。下面是SGI STL的声明:
template <class _Key, class _Tp, class _HashFcn = hash<_Key>, class _EqualKey =equal_to<_Key>,class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >class hash_map{...}也就是说,在上例中,有以下等同关系:...hash_map<int, string> mymap;//等同于:hash_map<int, string, hash<int>, equal_to<int> > mymap;

Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。

下面举例说明什么是一对一的数据映射。比如一个班级中,每个学生的学号跟他的姓名就存在着一一映射的关系,这个模型用map可能轻易描述,很明显学号用int描述,姓名用字符串描述(本篇文章中不用char *来描述字符串,而是采用STL中string来描述),下面给出map描述代码:

Map<int, string> mapStudent;

1.       map的构造函数

map共提供了6个构造函数,这块涉及到内存分配器这些东西,略过不表,在下面我们将接触到一些map的构造方法,这里要说下的就是,我们通常用如下方法构造一个map:

Map<int, string> mapStudent;

2.       数据的插入

在构造map容器后,我们就可以往里面插入数据了。这里讲三种插入数据的方法:

第一种:用insert函数插入pair数据,下面举例说明(以下代码虽然是随手写的,应该可以在VC和GCC下编译通过,大家可以运行下看什么效果,在VC下请加入这条语句,屏蔽4786警告  #pragma warning (disable:4786) )

#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent.insert(pair<int, string>(1, “student_one”));       mapStudent.insert(pair<int, string>(2, “student_two”));       mapStudent.insert(pair<int, string>(3, “student_three”));       map<int, string>::iterator  iter;       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){       Cout<<iter->first<<”   ”<<iter->second<<end;}}第二种:用insert函数插入value_type数据,下面举例说明#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent.insert(map<int, string>::value_type (1, “student_one”));       mapStudent.insert(map<int, string>::value_type (2, “student_two”));       mapStudent.insert(map<int, string>::value_type (3, “student_three”));       map<int, string>::iterator  iter;       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){       Cout<<iter->first<<”   ”<<iter->second<<end;}}第三种:用数组方式插入数据,下面举例说明#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent[1] =  “student_one”;       mapStudent[2] =  “student_two”;       mapStudent[3] =  “student_three”;       map<int, string>::iterator  iter;       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){       Cout<<iter->first<<”   ”<<iter->second<<end;}}

以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值,用程序说明

mapStudent.insert(map<int, string>::value_type (1, “student_one”));

mapStudent.insert(map<int, string>::value_type (1, “student_two”));

上面这两条语句执行后,map中1这个关键字对应的值是“student_one”,第二条语句并没有生效,那么这就涉及到我们怎么知道insert语句是否插入成功的问题了,可以用pair来获得是否插入成功,程序如下

Pair<map<int, string>::iterator, bool> Insert_Pair;

Insert_Pair = mapStudent.insert(map<int, string>::value_type (1, “student_one”));

我们通过pair的第二个变量来知道是否插入成功,它的第一个变量返回的是一个map的迭代器,如果插入成功的话Insert_Pair.second应该是true的,否则为false。

下面给出完成代码,演示插入成功与否问题

#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;Pair<map<int, string>::iterator, bool> Insert_Pair;       Insert_Pair = mapStudent.insert(pair<int, string>(1, “student_one”));       If(Insert_Pair.second == true)       {              Cout<<”Insert Successfully”<<endl;       }       Else       {              Cout<<”Insert Failure”<<endl;       }       Insert_Pair = mapStudent.insert(pair<int, string>(1, “student_two”));       If(Insert_Pair.second == true)       {              Cout<<”Insert Successfully”<<endl;       }       Else       {              Cout<<”Insert Failure”<<endl;       }       map<int, string>::iterator  iter;       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){       Cout<<iter->first<<”   ”<<iter->second<<end;}}大家可以用如下程序,看下用数组插入在数据覆盖上的效果#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent[1] =  “student_one”;       mapStudent[1] =  “student_two”;       mapStudent[2] =  “student_three”;       map<int, string>::iterator  iter;       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){       Cout<<iter->first<<”   ”<<iter->second<<end;}}

3.       map的大小

在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数,用法如下:

Int nSize = mapStudent.size();

4.       数据的遍历

这里也提供三种方法,对map进行遍历

第一种:应用前向迭代器,上面举例程序中到处都是了,略过不表

第二种:应用反相迭代器,下面举例说明,要体会效果,请自个动手运行程序


#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent.insert(pair<int, string>(1, “student_one”));       mapStudent.insert(pair<int, string>(2, “student_two”));       mapStudent.insert(pair<int, string>(3, “student_three”));       map<int, string>::reverse_iterator  iter;       for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++){       Cout<<iter->first<<”   ”<<iter->second<<end;}}第三种:用数组方式,程序说明如下#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent.insert(pair<int, string>(1, “student_one”));       mapStudent.insert(pair<int, string>(2, “student_two”));       mapStudent.insert(pair<int, string>(3, “student_three”));       int nSize = mapStudent.size()//此处有误,应该是 for(int nIndex = 1; nIndex <= nSize; nIndex++)//by rainfish       for(int nIndex = 0; nIndex < nSize; nIndex++){       Cout<<mapStudent[nIndex]<<end;}}

5.       数据的查找(包括判定这个关键字是否在map中出现)

在这里我们将体会,map在数据插入时保证有序的好处。

要判定一个数据(关键字)是否在map中出现的方法比较多,这里标题虽然是数据的查找,在这里将穿插着大量的map基本用法。

这里给出三种数据查找方法

第一种:用count函数来判定关键字是否出现,其缺点是无法定位数据出现位置,由于map的特性,一对一的映射关系,就决定了count函数的返回值只有两个,要么是0,要么是1,出现的情况,当然是返回1了

第二种:用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器,程序说明

#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent.insert(pair<int, string>(1, “student_one”));       mapStudent.insert(pair<int, string>(2, “student_two”));       mapStudent.insert(pair<int, string>(3, “student_three”));       map<int, string>::iterator iter;       iter = mapStudent.find(1);if(iter != mapStudent.end()){       Cout<<”Find, the value is ”<<iter->second<<endl;}Else{       Cout<<”Do not Find”<<endl;}}

第三种:这个方法用来判定数据是否出现,是显得笨了点,但是,我打算在这里讲解

Lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器)

Upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器)

例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper-bound(2)的话,返回的就是3

Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字,程序说明

#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent[1] =  “student_one”;       mapStudent[3] =  “student_three”;       mapStudent[5] =  “student_five”;       map<int, string>::iterator  iter;iter = mapStudent.lower_bound(2);{       //返回的是下界3的迭代器       Cout<<iter->second<<endl;}iter = mapStudent.lower_bound(3);{       //返回的是下界3的迭代器       Cout<<iter->second<<endl;} iter = mapStudent.upper_bound(2);{       //返回的是上界3的迭代器       Cout<<iter->second<<endl;}iter = mapStudent.upper_bound(3);{       //返回的是上界5的迭代器       Cout<<iter->second<<endl;} Pair<map<int, string>::iterator, map<int, string>::iterator> mapPair;mapPair = mapStudent.equal_range(2);if(mapPair.first == mapPair.second)       {       cout<<”Do not Find”<<endl;}Else{Cout<<”Find”<<endl;}mapPair = mapStudent.equal_range(3);if(mapPair.first == mapPair.second)       {       cout<<”Do not Find”<<endl;}Else{Cout<<”Find”<<endl;}}

6.       数据的清空与判空

清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map

7.       数据的删除

这里要用到erase函数,它有三个重载了的函数,下面在例子中详细说明它们的用法

#include <map>#include <string>#include <iostream>Using namespace std;Int main(){       Map<int, string> mapStudent;       mapStudent.insert(pair<int, string>(1, “student_one”));       mapStudent.insert(pair<int, string>(2, “student_two”));       mapStudent.insert(pair<int, string>(3, “student_three”)); //如果你要演示输出效果,请选择以下的一种,你看到的效果会比较好       //如果要删除1,用迭代器删除       map<int, string>::iterator iter;       iter = mapStudent.find(1);       mapStudent.erase(iter);        //如果要删除1,用关键字删除       Int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0        //用迭代器,成片的删除       //一下代码把整个map清空       mapStudent.earse(mapStudent.begin(), mapStudent.end());       //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合        //自个加上遍历代码,打印输出吧}

8.       其他一些函数用法

这里有swap,key_comp,value_comp,get_allocator等函数,感觉到这些函数在编程用的不是很多,略过不表,有兴趣的话可以自个研究

9.       排序

这里要讲的是一点比较高深的用法了,排序问题,STL中默认是采用小于号来排序的,以上代码在排序上是不存在任何问题的,因为上面的关键字是int型,它本身支持小于号运算,在一些特殊情况,比如关键字是一个结构体,涉及到排序就会出现问题,因为它没有小于号操作,insert等函数在编译的时候过不去,下面给出两个方法解决这个问题

第一种:小于号重载,程序举例

#include <map>#include <string>Using namespace std;Typedef struct tagStudentInfo{       Int      nID;       String   strName;}StudentInfo, *PStudentInfo;  //学生信息 Int main(){    int nSize;       //用学生信息映射分数       map<StudentInfo, int>mapStudent;    map<StudentInfo, int>::iterator iter;       StudentInfo studentInfo;       studentInfo.nID = 1;       studentInfo.strName = “student_one”;       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));       studentInfo.nID = 2;       studentInfo.strName = “student_two”;mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80)); for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)    cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl; }以上程序是无法编译通过的,只要重载小于号,就OK了,如下:Typedef struct tagStudentInfo{       Int      nID;       String   strName;       Bool operator < (tagStudentInfo const& _A) const       {              //这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序              If(nID < _A.nID)  return true;              If(nID == _A.nID) return strName.compare(_A.strName) < 0;              Return false;       }}StudentInfo, *PStudentInfo;  //学生信息第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明#include <map>#include <string>Using namespace std;Typedef struct tagStudentInfo{       Int      nID;       String   strName;}StudentInfo, *PStudentInfo;  //学生信息 Classs sort{       Public:       Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const       {              If(_A.nID < _B.nID) return true;              If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;              Return false;       }}; Int main(){       //用学生信息映射分数       Map<StudentInfo, int, sort>mapStudent;       StudentInfo studentInfo;       studentInfo.nID = 1;       studentInfo.strName = “student_one”;       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));       studentInfo.nID = 2;       studentInfo.strName = “student_two”;mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));}

10.   另外

由于STL是一个统一的整体,map的很多用法都和STL中其它的东西结合在一起,比如在排序上,这里默认用的是小于号,即less<>,如果要从大到小排序呢,这里涉及到的东西很多,在此无法一一加以说明。

还要说明的是,map中由于它内部有序,由红黑树保证,因此很多函数执行的时间复杂度都是log2N的,如果用map函数可以实现的功能,而STL  Algorithm也可以完成该功能,建议用map自带函数,效率高一些。

下面说下,map在空间上的特性,否则,估计你用起来会有时候表现的比较郁闷,由于map的每个数据对应红黑树上的一个节点,这个节点在不保存你的数据时,是占用16个字节的,一个父节点指针,左右孩子指针,还有一个枚举值(标示红黑的,相当于平衡二叉树中的平衡因子),我想大家应该知道,这些地方很费内存了吧,不说了……

1 0
原创粉丝点击