我注意到 std::unordered_map
的 insert
函数返回一个 std::pair
。
std::pair
的第二个元素显示是否真的插入了值。但是,我对此感到困惑。由 HashMap 实现的 std::unordered_map
是否会在插入时失败?什么时候会发生?
这是在 cppreference 的描述:
Return value
1-2) Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place.
最佳答案
从您链接到的同一页面:
Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.
(我的重点)
换句话说,如果键已经存在于映射中,则 bool
为 false
。
请注意,其他失败(如分配失败)将通过异常报告(并且容器将保持不变)。
关于c++ - std::unordered_map::insert 什么时候会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858356/