【C++】STL进阶-- 哈希结构的关联式容器(unordered_map和unordered_set)

哈希结构,简单来说就是通过设定哈希函数使元素的存储位置与它的关键码之间可以建立一一映射的关系,那么在查找关键码时,可以通过该函数计算结果很快找到该元素的一种方法。因此在哈希表中搜索数据的时间复杂度会被认为是"平均为O(1)的复杂度"。
unordered系列的关联式容器之所以效率比较高,是因为其底层用了哈希结构,想了解的哈希结构的可以移步这篇博客哈希结构–哈希冲突解决方法(闭散列)。下面我就介绍一下unordered系列两个容器的使用。

1. unordered_map的使用示例

大家可以查看unordered_map文档了解详情,下面我简单总结一下:

  1. unordered_map是存储<key, value>键值对的关联式容器,其允许通过keys快速的索引到与其对应的 value。
  2. 在unordered_map中,键值通常用于惟一地标识元素,而映射值是一个对象,其内容与此键关联。键 和映射值的类型可能不同。
  3. 在内部,unordered_map没有对<kye, value>按照任何特定的顺序排序, 为了能在常数范围内找到key所 对应的value,unordered_map将相同哈希值的键值对放在相同的桶中。
  4. unordered_map容器通过key访问单个元素要比map快,但它通常在遍历元素子集的范围迭代方面效率 较低。
  5. unordered_maps实现了直接访问操作符(operator[]),它允许使用key作为参数直接访问value。
  6. 它的迭代器至少是前向迭代器。

接口说明:

bool empty()const
检测unordered_map 是否为空
operator[ ]
返回与key对应的value,没有一个默认值
注意: 该函数实际调用哈希桶的插入操作,用参数key与v()构造一个默认值往底层哈希桶中插入,如果key不在哈希桶中,插入成功,返回V(),插入失败,说明key已经存在哈希桶中,将key对应的value返回。
iterator find(const K&key)
返回key在哈希桶中的位置
size_t count(const K&key)
返回哈希桶中关键码为key 的键值对的个数
注意: unordered_map中key是不能重复的,因此count返回的最大值是1。

接口使用示例代码

#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>

using namespace std;

int main()
{
	unordered_map<string, string> um;
	um.insert(make_pair(string("sort"), string("排序")));
	um.insert(make_pair(string("string"), string("字符串")));
	um.insert(make_pair(string("left"), string("左边")));
	um.insert(make_pair(string("lost"), string("丢失")));
	um.insert(make_pair(string("come"), string("过来")));
	
	cout << um.empty() << endl;//判断是否为空
	cout << um.size() << endl;//元素的个数


	unordered_map<string, string>::iterator it = um.begin();
	while (it != um.end())
	{
		cout << it->first << ":" << it->second << endl;
		++it;
	}

	return 0;
}

在这里插入图片描述

2.unordered_set

大家可以查看unordered_set 文档了解详情:

接口使用示例

int main()
{
	unordered_set<int> us;
	us.insert(9);
	us.insert(6);
	us.insert(8);
	us.insert(10);
	us.insert(7);
	us.insert(3);
	us.insert(6);
	us.insert(7);
	us.insert(4);

	cout << us.empty() << endl;
	cout << us.size() << endl;

	unordered_set<int>::iterator it = us.begin();
	while (it != us.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	system("pause");
	return 0;
}

在这里插入图片描述

除此之外,我还介绍了树形结构的关联式容器,有兴趣的可以点击查看STL进阶-- 树形结构的关联式容器(map和multimap),看完记得关注下博主哦~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值