语言联邦-C++标准库与哈希表

1.标准C++库(STL)中有哈希容器吗?
C++11正式发表(2012年)之前,STL中没有哈希容器。每个人都认为这是一个遗憾,但是C++标准委员会认为,把它们加入标准中所需的工作会拖延标准完成的时间。
C++11中新增了哈希容器,其定义位于头文件 中,且C++11新引入的两组无序容器(PS:C++11之前标准库中的关联容器全部基于排序)std::unordered_map/std::unordered_multimap/std::unordered_set/std::unordered_multiset 默认采用哈希结构为键值计算[哈希代码]。

//计算值的[哈希代码]
template
struct hash {
size_t operator()(Ty val) const;
};
C++11对基本类型提供专用化:Ty 可能为任何标量类型,包括指针类型和枚举类型。 此外,还具有库类型 string、wstring、u16string、u32string、string_view、wstring_view、u16string_view、u32string_view、bitset、error_code、error_condition、optional、shared_ptr、threadtype_index、unique_ptr、variant 和 vector 的专用化。
2.哈希容器怎么使用?

#include "stdafx.h"
#include <functional>
#include <iostream>
#include <unordered_set>
#include <algorithm>

int main()
{
	using StringHashSet = std::unordered_set<std::wstring, std::hash<std::wstring>>;
	StringHashSet ssp;
	ssp.insert(L"spring");
	ssp.insert(L"summer");
	ssp.insert(L"autumn");
	ssp.insert(L"winter");
	//打印哈希代码
	for_each(ssp.begin(), ssp.end(),
		[](const auto& sKey) {std::cout <<*sKey.c_str() << std::endl;});
	//查找
	std::wstring wsValue = *(ssp.find(L"spring"));
	std::cout << "查找 spring :" << *wsValue.c_str() << std::endl;
	wsValue = *(ssp.find(L"summer"));
	std::cout << "查找 summer :" << *wsValue.c_str() << std::endl;

	return (0);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值