[温习C/C++]0x08 C++刷题技巧—关联容器使用operator[]访问避坑

系列文章目录

[温习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[]访问避坑

C++刷题技巧—关联容器使用[]访问避坑

考点

考察 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值