系列文章目录
[温习C/C++]0x00-STL标准模板库概述
[温习C/C++]0x01-STL泛型算法-持续更新长文版
[温习C/C++]0x03-sort排序
[温习C/C++]0x04 C++刷题基础编码技巧
[温习C/C++]0x05 C++刷题技巧—set自定义排序及查找
[温习C/C++]0x06 坐标系中矩形重叠类问题分析
[温习C/C++]0x07 C++刷题技巧—字符串查找find、find_if、find_first_of和find_last_of
[温习C/C++]0x08 C++刷题技巧—关联容器使用operator[]访问避坑
考点
考察 map::operator[]的行为。
问题代码
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> myMap{{"A", 1},
{"B", 2},
{"C", 3}};
string name[] = {"A", "B", "C", "D"};
int cnt = 0;
for (const auto& nm : name) {
cnt += myMap[nm];
}
cout << "myMap size = " << myMap.size() << endl;
return 0;
}
输出:
A : 1
B : 2
C : 3
D : 0
myMap size = 4
分析
关联容器[]访问,如果key值不存在,则执行insert val。
从结果:
A : 1
B : 2
C : 3
D : 0

知识点总结
| 知识点 | 说明 |
|---|---|
std::map::operator[] | 如果key存在,返回对应值的引用;如果不存在,插入新建并将值默认初始化 |
| 有序性 | map内存按照key排序存储 |
- 误区
认为map::operator[]不存在的时候会报错,其实它会插入新元素。题目代码中的场景,建议使用find:
int cnt = 0;
for (const auto& nm : name) {
const auto iter = myMap.find(nm);
if (iter != myMap.end()) {
cnt += iter->second;
}
}
- 使用
at()替代operator[]看看会不会抛异常。
int cnt = 0;
for (const auto& nm : name) {
cnt += myMap.at("F"); // std::out_of_range
}
运行时错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): map::at

被折叠的 条评论
为什么被折叠?



