如何在不插入std::unordereded_map元素的情况下访问(检查)该元素

How do I access (check) the element of a std::unordered_map without inserting into it?

本文关键字:元素 情况下 访问 检查 插入 std unordereded map      更新时间:2023-10-16

使用[]运算符访问std::unorderede_map的元素会插入新元素:

std::unordered_map<std::string, uint32_t> umap = {
    {"Thomas", 1},
    {"Frank", 5},
    {"Lisa", 7}
};
// umap.size() is 3
uint32_t id = umap["Lisa"];
// umap.size() is 3
id = umap["Randy"]; // key "Randy" doesn't exist
// umap.size() is 4

我天真地以为[]运算符在没有右侧赋值的情况下会表现为只读。在访问密钥之前,我是否必须通过count()find()检查密钥是否存在,或者是否有其他选择?

是的,您必须使用find:进行检查

if (umap.find("Randy") == umap.end()) // does not exist

除了find()count()之外,另一种选择是at()方法,如果不存在,它会抛出异常。

相关文章: