为什么空 unordered_map.find 不返回 end()?

Why is empty unordered_map.find not returning end()?

本文关键字:end 返回 find unordered map 为什么      更新时间:2023-10-16

我正在尝试测试给定键是否已经存在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;
}
相关文章: