c++ - 为什么空的 unordered_map.find 不返回 end()?

标签 c++ unordered-map stdstring

<分区>

我正在尝试测试 unordered_map 中是否已经存在具有给定键的条目。我正在使用 find() 函数返回一个迭代器。问题是 unordered_map 是否为空(或不为空),当没有带有给定键的条目时,它会返回一个“空”对象,就像这样 -

it = (<Error reading characters of string.>, -842150451)

我已经尝试创建一个空的项目解决方案并放入一个最小的示例。它仍然为 find() 返回相同的“空”对象。我什至尝试将键的类型从 std::string 更改为 int,结果相同。

#include <unordered_map>

int main(int argc, char* argv[])
{
    std::string key = "test";
    std::unordered_map<std::string, int> myMap;
    myMap["abc"] = 5;
    std::unordered_map<std::string, int>::iterator it = myMap.find(key);
}

我期望 find() 在没有具有给定键的条目时返回“end”,但输出是某种“空”对象。

最佳答案

只需将迭代器与列表末尾进行比较,例如

  if (it == myMap.end()) {
    std::cout << "didn't find" << std::endl;
  } else {
    std::cout << "found " << it->second << std::endl;
  }

关于c++ - 为什么空的 unordered_map.find 不返回 end()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57529681/

相关文章:

c++ - 为什么 std::string 对象的最大大小是 4611686018427387897?

c++ - 限制 std::string 分配的数量

c++ - QWidget 每像素半透明

c++ - 读取二进制文件并转换为整数数组时出现问题

c++ - 初始化我的 std::map

c++ - 对同一对象同时使用 Map 和 List

c++字符串到char *的隐式转换匹配错误的函数签名

c++ - 从源代码静态链接 GLEW 与 cmake

c++ - C++ 中 unordered_maps 与 unordered_multimaps 的底层存储和功能?

c++ - CDT 索引器找不到 std::unordered_map