热门问题
时间线
聊天
视角
无序关联容器 (STL)
来自维基百科,自由的百科全书
Remove ads
C++程序设计语言中,unordered_map、unordered_multimap、unordered_set、unordered_multiset是标准模板库(STL)提供的一类无序关联容器(unordered associative containers)。是通过哈希表实现的数据结构。无序是指元素的名字(或者键值)的存储是无序的;这与用平衡二叉树实现的元素名字是有序存储的“关联容器”是相对概念。
历史
SGI的STL提供了hash_map, hash_set, hash_multimap, hash_multiset等类模板。[1]由于其有用性,很快其它的C++编译器也支持了这一特性,如GCC、 libstdc++[2] 以及MSVC (在stdext命名空间)。
C++ TR1语言标准中提出了增加hash_*类模板[3],最终接受为unordered_*。 [4] Boost C++ Libraries也提供了一种实现。<boost/unordered_map.hpp>.[5]
类成员函数
头文件<unordered_map>中定义了类模板unordered_map。并满足容器 (页面存档备份,存于互联网档案馆)概念,这意味着它支持begin()、end()、size()、max_size()、empty()、 swap()等方法。
Remove ads
例子
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, int> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
std::cout << "september -> " << months["september"] << std::endl;
std::cout << "april -> " << months["april"] << std::endl;
std::cout << "december -> " << months["december"] << std::endl;
std::cout << "february -> " << months["february"] << std::endl;
//判断map中是否包含一个键值,没有直接做此事的成员函数。类似其他的STL容器,解决办法是:
if( months.find("no_value") == months.end() )
{
printf("No such key in the map.");
}
return 0;
}
定制哈希函数
定制的哈希函数的参数为到定制类型的const引用,返回类型为size_t
struct X{int i,j,k;};
struct hash_X{
size_t operator()(const X &x) const{
return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
}
};
定制哈希函数作为std::unordered_map的模板参数使用。
std::unordered_map<X,int,hash_X> my_map;
或者通过特化std::hash来使用。
namespace std {
template <>
class hash<X>{
public :
size_t operator()(const X &x ) const{
return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
}
};
}
//...
std::unordered_map<X,int> my_map;
Remove ads
参考文献
Wikiwand - on
Seamless Wikipedia browsing. On steroids.
Remove ads