容器类之 unordered_map
来源:互联网 发布:linux版本的abaqus6.16 编辑:程序博客网 时间:2024/05/06 09:24
该容器的特点
- 存放数据的方式:
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::vectorint 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()
:打印错误流中的信息。
0 0
- 容器类之 unordered_map
- STL无序容器之unordered_map
- TR1 五种新容器 之 unordered_set unordered_multiset unordered_map unordered_multimap
- 关联容器(五):unordered_map
- STL之unordered_map
- boost之unordered_map
- 哈希表之unordered_map
- C++11 unordered_map 无序容器的使用
- C++关联容器(unordered_map,vector,unordered_set)
- 【Leetcode】 1.two sum unordered_map 关联容器
- unordered_map
- unordered_map
- unordered_map
- unordered_map
- unordered_map -
- unordered_map
- unordered_map
- unordered_map
- HDU 3111 Sudoku(数独,还是深搜)
- 关于双目立体视觉的一些总结(二)
- 338. Counting Bits 数字的二进制中1的个数
- android开发中的ContextMneu(上下文菜单)
- FZU Problem 2230 翻翻棋
- 容器类之 unordered_map
- 05Android Studio使用插件推荐
- bzoj 1188: [HNOI2007]分裂游戏(sg函数)
- linux find 命令忽略某个或多个子目录的方法
- traits简单认识
- CoreThink主题开发(八)使用H-ui开发博客主题之用户登录之前及登录之后
- hdu1010 扩展KMP求字符串最小循环节
- 获取和推送镜像
- android:screenOrientation属性