该容器的特点
- 存放数据的方式:
key = value
,通过key
进行检索。 - 存放数据时无序的。
- 检索的速度比
map
类快。 - 重载了
[ ]
运算符。 iterator
可以访问key
和value
。unordered_map<int, bool> m = { { 5, true }, { 6, true } }; unordered_map<int, bool>::iterator it = m.begin(); int key = it->first; bool b = it->second;
与检索相关的成员函数
operator[key]
查找成功:返回
value
的引用(reference)。查找失败:在
map
后面插入一个新的元素,key
为当前查找的值,value
在未赋值的情况下是为空的。// unordered_map::operator[] #include <iostream> #include <string> #include <unordered_map> using namespace std; int main () { unordered_map<string,string> mymap; mymap["Bakery"]="Barbara"; // not found, new element inserted mymap["Seafood"]="Lisa"; // not found, new element inserted mymap["Produce"]="John"; // not found, new element inserted string name = mumap["XXXXX"]; // not found, the new element inserted, but the value is NULL. for (auto& x: mymap) { cout << x.first << ": " << x.second << endl; } return 0; } output result: Bakery: Barbara Seafood: Lisa Produce: John XXXXX:
auto& x : mymap
:使用智能指针进行遍历。find(key)
查找成功:返回一个
iterator
,指向该元素。查找失败:返回一个
iterator
,指向map.end()
。at(key)
查找成功:返回引用。
查找失败:抛出
out_of_range
(#include <stdexcept>
)异常。#include <iostream> // std::cerr #include <stdexcept> // std::out_of_range #include <vector> // std::vector int main (void) { std::unordered_map<int, bool> m = { { 5, true }, { 6, true } }; int i = 7; try { m.at(i); //find the value of which the key is 7. } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << '\n'; std::cerr << "Out of Range error: " << "the key " << i << " not found." << '\n'; } return 0; }
orr.what()
:打印错误流中的信息。