c++ - 映射运算符 [] 和 bool 作为值

标签 c++ stl map

我们知道,如果我们尝试访问一个不存在的键 std::map使用运算符 [] ,该函数将使用该键插入一个新元素。

我们有:std::map<std::string, bool> map_xxx;

是否保证访问map_xxx["nonexistent_key"]不存在的key后,第二个参数的值将始终为 false ?

ps。如果没有,任何想法如何有这种行为?

最佳答案

是的。插入的值保证为false


在 C++98 中,该机制被称为默认初始化,指定为非类的零初始化;这是 bool 值的 false

从C++03开始,该机制称为值初始化,对于非类仍然指定为零初始化;因此对于 bool 值仍然是 false 。例如,让我们看看 C++14 对此有什么看法。

来自第 23.4.4.3 节;只需将 bool 替换为“T”即可。

T& operator[](const key_type& x);

  1. Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
  2. Requires: key_type shall be CopyInsertable and mapped_type shall be DefaultInsertable into *this.

从第 8.5 节开始,自下而上消化段落:

To zero-initialize an object or reference of type T means:

— if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;

...

To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;

— if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;

— if T is an array type, then each element is value-initialized;

— otherwise, the object is zero-initialized.

...

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

从 §4.12:

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

关于c++ - 映射运算符 [] 和 bool 作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11058422/

相关文章:

c++ - std::deque 在末尾插入是否比 std::vector 快?

c++ - std::vector 的高性能替代品

c++ - IEEE float std::map 和 std::set 的有效键类型吗?

java - 如何运行/调试具有特定工作目录的 Netbeans 平台应用程序?

c++ - 预测 FFT 的拖尾

c++ - 包含头文件 unordered_map 时出错

Android Map API v2 在某些设备上不显示 map

c++ - std::multimap 如何存储它的元素?

c++ - 如何进行特定的位操作?

java - 如何使用其键和值属于特定层次结构的通用映射?