c++ - std::unordered_map::insert 什么时候会失败?

标签 c++ c++11 insert unordered-map

我注意到 std::unordered_mapinsert 函数返回一个 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.

(我的重点)

换句话说,如果键已经存在于映射中,则 boolfalse

请注意,其他失败(如分配失败)将通过异常报告(并且容器将保持不变)。

关于c++ - std::unordered_map::insert 什么时候会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858356/

相关文章:

c++ - 内存区域和内存分配器有什么区别?

c++ - 有没有办法在正弦方程中设置像 “unknown”这样的 “x”变量,然后再更改其值?

c++ - Gstreamer rtsp流到appsink到openCV

C++ 引用构造函数语法

C++ 如何在单个定义中的多个声明符中定义 const 引用?

c++ - 通过传递指针的地址来初始化 std::unique_ptr

php - 我可以避免在 INSERT 查询中用 NULL 值覆盖列吗?

php - INSERT ON DUPLICATE KEY UPDATE 多行,检查每行的重复项

c++ - 为什么不调用移动构造函数?

mysql - 使用子查询 MySQL 插入 INTO