如何在不插入std::unordereded_map元素的情况下访问(检查)该元素
How do I access (check) the element of a std::unordered_map without inserting into it?
使用[]运算符访问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()
方法,如果不存在,它会抛出异常。
相关文章:
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 如何在不迭代的情况下对数组中的每个元素调用方法
- 是否可以在不复制的情况下访问undered_map中的元素
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 我怎样才能在不重复的情况下随机迭代向量的每个元素
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- 在这种情况下,如何返回对数组中元素的引用?
- 是否可以在不显式迭代每个元素的情况下深度复制指针容器?
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- 在不调用构造函数的情况下创建 Vector 元素
- 在C++中,如何在没有新元素且不单独声明单个元素的情况下创建"std::initializer_list<base *>"?
- 如何在使用和无发现的情况下使用和不使用的字符串向量搜索元素
- 如何在不使用循环或迭代器的情况下检查所有列表元素并在满足条件时删除一个
- 如何在不使用 C++ 函数的情况下显示链表中的元素
- 如何在给定迭代器列表的情况下从向量中删除元素
- 我如何在C 中制作算法,以在不重复的情况下查找集合的变化(即n元素,选择k)
- 如何在不知道大小的情况下编写过程来修改动态数组的元素和大小
- 如何在不修改现有函数的情况下反转数组中除第一个和最后一个元素之外的所有元素