C++ STL中map的[]操作符使用时的一个坑

前言

学习C++,自从发现了map这个结构以后,就深深的被这种键值对的方式吸引了,写代码时也渐渐离不开这种结构了,一次偶然的机会发现这个map还有个 [] 运算符,仿佛又发现了新大陆一样,写代码更加方便了,殊不知一个深深的大坑正在前面等着我。

问题

一开始学到map的时候还是中规中矩的使用函数插入删除,比如定义一个map,先引入头文件和命名空间:

#include <map>
using namespace std;

map<int, int> mapTest;

上面就轻松定义了一个map结构对象,是一个整数到另一个整数的映射,这种映射有什么用呢?举个简单的例子,这个映射可以作为学生的学号和成绩的对应关系,这样只要知道学号,就可以从map中直接获得对应的成绩很方便。

最开始学习插入时通常有以下两种方式:

mapTest.insert(map<int, int>::value_type(1001, 100));
mapTest.insert(make_pair(1002, 98));

但是学了 map[] 操作符以后,上述代码可以写成:

mapTest[1001] = 100;
mapTest[1002] = 98;

查找一个元素的时候需要用到find()函数,一般写成

map<int, int>::const_iterator itor = mapTest.find(1001);
if (itor != mapTest.end())
    return itor->second;

但是学了 map[] 操作符以后,上述代码就可以简写成:

return mapTest[1001];

特别的在插入一个元素的时候,比如用来计数,每次给一个键对应的值加1时,可以直接写成:

mapTest[1001] += 1;

根本不用检查 1001 这个键是否存在,使用 [] 操作符,在使用前会先默认成0,然后执行+1操作,这个比先使用find()查找,然后+1操作后再插入方便多了。

其实这只是使用map结构的一种语法糖,但是这语法糖简直太好使了,太甜了,让人欲罢不能,所以我就含着这块糖掉进了坑里,因为调用 map 的有时会产生副作用,如果查找一个键不在 map 中,则会在map中对应的这个键的位置插入默认值,接下来看一下例子就明白了。

测试过程

测试代码在VS2015中编译运行,C++11标准,如果编译不正确可以看一下环境是否不同,尝试修改代码实现即可,测试的例子也是上面提到的,使用 map 来存储学生学号和成绩的对应关系,下面来简单实现一个类,描述这种关系:

编写测试类

#include <map>
#include <iostream>
#include <algorithm>
using namespace std;

class CReportCard
{
public:
    CReportCard() { m_mapStuNo2Score.clear(); }
    ~CReportCard() { m_mapStuNo2Score.clear(); }
public:
    void LoadScores(); // 模拟录入成绩
    int  GetScoreByStudentNo(const int nStudentNo); // 根据学号查询成绩
    void PrintReportCard(); // 打印成绩单
private:
    map<int, int> m_mapStuNo2Score;
};

void CReportCard::LoadScores()
{
    m_mapStuNo2Score[1001] = 99;
    m_mapStuNo2Score[1002] = 94;
    m_mapStuNo2Score[1004] = 89;
    m_mapStuNo2Score[1005] = 92;
    m_mapStuNo2Score[1007] = 80;
}

int CReportCard::GetScoreByStudentNo(const int nStudentNo)
{
    return m_mapStuNo2Score[nStudentNo];
}

void CReportCard::PrintReportCard()
{
    cout << "show report card start----->" << endl;
    std::for_each(m_mapStuNo2Score.begin(), m_mapStuNo2Score.end(), [](std::map<int, int>::reference socrepair)
    {
        std::cout << socrepair.first << "'s score = " << socrepair.second << "\n";
    });
    cout << "show report card end<------" << endl;
}

这个类的内容很简单,使用 map 类型的对象 m_mapStuNo2Score 来存储学号和成绩的对应关系,LoadScores()函数中使用 [] 操作符向 map 中插入元素,模拟成绩录入过程;GetScoreByStudentNo()函数同样使用了 [] 操作符模拟成绩查询过程;PrintReportCard()函数遍历 map 打印成绩单信息。

看似正常的调用

接下来编写一个函数来使用这个类,测试如下:

int main(int argc, char* argv[])
{
    CReportCard obj;
    obj.LoadScores();

    cout << "student no = 1001, score = " << obj.GetScoreByStudentNo(1001) << endl;
    cout << "student no = 1004, score = " << obj.GetScoreByStudentNo(1004) << endl;

    obj.PrintReportCard();

    return 0;
}

首先调用 LoadScores()函数来加载数据,然后通过 GetScoreByStudentNo() 函数来查找学号为 10011004 的两个学生的成绩,最后打印一下成绩单,接下来看一下运行结果:

student no = 1001, score = 99
student no = 1004, score = 89
show report card start----->
1001’s score = 99
1002’s score = 94
1004’s score = 89
1005’s score = 92
1007’s score = 80
show report card end<------

以上结果正常的打印出了查询的分数和成绩单,一切看起来毫无问题,如果查询的学号不存在又会怎么样呢?

出现问题的调用

修改上面的测试函数,将学生学号改成不存在的数值,修改如下:

int main(int argc, char* argv[])
{
    CReportCard obj;
    obj.LoadScores();

    cout << endl;
    cout << "student no = 1011, score = " << obj.GetScoreByStudentNo(1011) << endl;
    cout << "student no = 1014, score = " << obj.GetScoreByStudentNo(1014) << endl;

    obj.PrintReportCard();

    return 0;
}

大部分的内容并没有发生变化,只将学号改成了不存在的情况,测试结果如下:

student no = 1011, score = 0
student no = 1014, score = 0
show report card start----->
1001’s score = 99
1002’s score = 94
1004’s score = 89
1005’s score = 92
1007’s score = 80
1011’s score = 0
1014’s score = 0
show report card end<------

不存在的学号对应的分数是0,这应该也说的过去,因为键不存在,所以对 map 使用 [] 操作符查找时,寻找的键不存在则返回了整型的默认值0,但是在打印成绩单的时候居然多了两项,这充分暴露了 [] 操作符可能产生的副作用。

在查找返回时,[] 操作符并不是找不到返回对应类型默认值就完了,还会把查找的键和默认值作为一对,插入到待查的 map,这种操作一般是我们不需要的,所以在你明确不需要这个副作用时,查找 map 元素不要使用 [] 操作符。

亡羊补牢

上面说到,[] 操作符查找不到就插入的副作用一般我们不使用,所以在查找时还是使用 find() 函数更规范一些,修改 GetScoreByStudentNo() 函数如下:

int CReportCard::GetScoreByStudentNo(const int nStudentNo)
{
    //return m_mapStuNo2Score[nStudentNo];
    map<int, int>::const_iterator itor = m_mapStuNo2Score.find(nStudentNo);
    return itor != m_mapStuNo2Score.end() ? itor->second : 0;
}

此时再运行上面的例子就正常了,成绩单中也不会插入无效值了。

总结

  1. map[] 操作符会有副作用,当查找的键不存在时,会在对应键位置插入默认值
  2. 时刻保持清醒的头脑,过分的方便或许会给你自己埋下深深的坑
  3. 敬畏自然、敬畏生命、敬畏你写下的每一行代码
发布了150 篇原创文章 · 获赞 277 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/shihengzhen101/article/details/103529462