刚刚用到了unordered_map,来学习一下。
顾名思义,这就是无排序的map结构。
模板定义如下:
template < class Key, // unordered_map::key_type
class T, // unordered_map::mapped_type
class Hash = hash<Key>, // unordered_map::hasher
class Pred = equal_to<Key>, // unordered_map::key_equal
class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type
> class unordered_map;
包括键值对,hash规则,比较规则以及指定分配器对象的类型。
在内部,unorder_map中的元素不按照其键或映射值的任何特定顺序进行排序,而是根据它们的哈希值组织成桶,以允许通过它们的键值直接快速访问单个元素(平均时间复杂度恒定)。
关于构造一个unordered_map有四种方法:
1、空构造
2、拷贝构造
3、移动构造
4、范围构造
5、初始值构造
下面看一个官方示例代码了解一下:
// constructing unordered_maps
#include <iostream>
#include <string>
#include <unordered_map>
typedef std::unordered_map<std::string,std::string> stringmap;
stringmap merge (stringmap a,stringmap b) {
stringmap temp(a); temp.insert(b.begin(),b.end()); return temp;
}
int main ()
{
stringmap first; // empty
stringmap second ( {{"apple","red"},{"lemon","yellow"}} ); // init list
stringmap third ( {{"orange","orange"},{"strawberry","red"}} ); // init list
stringmap fourth (second); // copy
stringmap fifth (merge(third,fourth)); // move
stringmap sixth (fifth.begin(),fifth.end()); // range
std::cout << "sixth contains:";
for (auto& x: sixth) std::cout << " " << x.first << ":" << x.second;
std::cout << std::endl;
return 0;
}
函数 | 功能 |
---|---|
begin | 返回第一个键值对的正向迭代器 |
end | 返回最后一个键值对后一个位置的正向迭代器 |
cbegin | 和begin相同,但是增加了const属性,则返回的迭代器不能用于修改内容 |
cend | 和end相同,但是增加了const属性,则返回的迭代器不能用于修改内容 |
empty | 空则返回true,否则返回false |
size | 返回键值对个数 |
max_size | 返回最大容纳的键值对个数,不同系统结果不一样 |
operator[key] | 像数组一样可以通过下标操作,若当前下标没有键对值,则插入新的键对值 |
at(key) | 返回key对应的值,若不存在,返回out_of_range异常 |
前人用unordered_map踩的坑:unordered_map的坑
更多的信息可以去官网看看:STL:unordered_map
或者看看: 编程网