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);
}