【问题标题】:Program crashes on trying to access the key that does not exist in map [duplicate]尝试访问地图中不存在的密钥时程序崩溃[重复]
【发布时间】:2020-07-24 09:46:08
【问题描述】:

我正在做一个简单的程序,试图获取地图中不存在的键值对。但是当我运行代码时,我得到一个运行时错误,说==8406==WARNING: AddressSanitizer failed to allocate 0x7ffe7f82c881 bytes ==8406==AddressSanitizer's allocator is terminating the process instead of returning 0 ==8406==If you don't like this behavior set allocator_may_return_null=1

#include <iostream>
#include <map>
#include <string>

int main ()
{
    typedef std::map<std::string,int> mymap;
    mymap cnt;

    cnt["a"]=10;

    auto f = first.find("asdasd");
    std::cout << f->second;
    return 0;
}

在我做f-&gt;second的那一行。如何处理地图中不存在密钥的情况?

【问题讨论】:

  • “我如何处理地图中不存在密钥的情况” - 简单。只需检查map::end

标签: c++ stl iterator


【解决方案1】:

如果键不存在,std::map 特化的 find 成员函数会返回一个过去的迭代器。

所以你需要对比容器的end():

 auto f = cnt.find("asdasd");
 if (f != cnt.end()) {
     std::cout << f->second;
 }

【讨论】:

    【解决方案2】:

    假设你的意思

    auto f = cnt.find("asdasd");
    

    您需要检查您查找的密钥是否确实存在

    if (f != cnt.end())
        std::cout << f->second;
    

    否则,您将取消引用无效位置,那就是 UB。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2017-05-22
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多