C++ STL map 【避坑】 中括号查找(map[.])导致超时

发布时间 2023-05-04 12:08:00作者: killerboom

感谢大神的博客:STL map关于查找的坑——尽量不使用方括号[ ]查找_stl map 查找_sdudyl的博客-CSDN博客

今天在CF补了一道题,我开了map使用中括号查找,结果第二组就T了。

我百思不得其解,最后把map[x]换成map.count(x)就过了。

因为这样使用中括号查找x时,如果找不到x,会向容器中插入一个x。这道题查找值域很大,于是乎T了。

这样一个例子:

#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
    map<string, bool> book;
    book["sdu"] = true;
    book["csp"] = true;
    if (book["ccf"])
        cout << "yes" << endl;
    for (map<string, bool>::iterator it = book.begin(); it != book.end(); it++)
        cout << it->first << " ";
}

我们希望他的输出是 sud csp,但结果是:

 以后要注意一下。