C++| STL之unordered_map(哈希表)和map

前言:Leetcode题目中有一个哈希表的专题,自己实现的话没必要,可以直接用STL现成的unordered_map函数,提到unordered_map就不得不提到map,于是有了此篇相关知识点的汇总。

key和value

unordered_map和map都是一个将key和value关联起来的容器,可以根据key来查找对应的value,类似于其它语言中的字典。

其中key是唯一的,key和value的数据类型可以不同。

unordered_map

unordered_map其实就是stl提供的哈希表的工具。

使用

头文件:

#include<unordered_map>

声明和初始化:

unordered_map<int, int> hmap;// 关键字、键对值的类型都是int
unordered_map<int, int> hmap{ {1,5},{2,6},{3,7} };
unordered_map<int, int> hmap{ {{1,5},{2,6},{3,7}},3 };
unordered_map<int, int> hmap1(hmap);// 通过复制已经初始化的哈希表来构建新的表

添加元素:

// 1. 下标
hmap[4] = 8;
// 2. insert函数,同一个位置第二次insert会失败
hmap.insert({ 5,9 });
// 3. insert+pair
hmap.insert(make_pair(6, 10));
pair<int, int>p(7, 11);
hmap.insert(p);
// 4. emplace函数,相比与insert不需要手动创建键对值
hmap.emplace(8, 12);

访问:

int a=hmap[4];// 下标
int b=hmap.at(4);// at

迭代器遍历:

for(unordered_map<int,int>::iterator iter=hmap.begin();iter!=hmap.end();iter++)
          cout<<"key "<<iter->first<<" value "<< iter->second;

查找:

if(hmap.find(x) != hmap.end())
	cout<<x<<"存在"<<endl

删除元素:

hmap.erase(5);// 删除key为5的内容
hmap.clear();// 清空

容量:

bool isEmpty = hmap.empty();
int size = hmap.size();

交换:

hmap1.swap(hmap2);// 交换两个哈希表的内容

map

原理对比unordered_map

map的特点是有序性,unordered_map的特点是无序性。

原因在于实现原理,map实现原理是红黑树,具有自动排序,内部的所有元素都是有序的,和插入顺序相同;unordered_map实现原理是哈希表,所以内部元素排序是无序的。

运行效率上,unordered_map查找速度比map快,但建立比较废时间。
占用内存上,map红黑树需要额外的空间保存每个节点的父节点和孩子节点,空间占用率会高。

使用对比unordered_map

map的话,常见的使用和unordered_map差不多,但是有些地方要注意。

头文件和声明类型需要从unordered_map写成map。

#include<map>
map<int, int> mp;

map是有序的,声明的时候可以说明排序准则,一般按照键(key)的升序进行排序的。

// 1. 降序的map
map<int, string, greater<int>> mpDesc;
// 1. 自定义排序准则
// 这个是结构体里面的,和sort的还不太一样,sort是函数只对线性容器进行排序
struct Cmp {  
	// 这里的const一定不能省略
    bool operator()(const int& a, const int& b) const {  
        return a>b;  
    }  
};   
std::map<int, int, Cmp> mpDesc;// 降序

因为map是有序的,所以迭代器遍历的时候也是按照key的顺序来的。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值