如果我在键不存在的情况下读取地图的值会发生什么?

2021-12-10 00:00:00 c++ map
map<string, string> dada;
dada["dummy"] = "papy";
cout << dada["pootoo"];

我很困惑,因为我不知道它是否被认为是未定义的行为,如何知道我何时请求不存在的密钥,我是否只使用 find ?

I'm puzzled because I don't know if it's considered undefined behaviour or not, how to know when I request a key which does not exist, do I just use find instead ?

推荐答案

map::operator[] 在数据结构中搜索与给定键对应的值,并返回对它的引用.

The map::operator[] searches the data structure for a value corresponding to the given key, and returns a reference to it.

如果它找不到一个,它会透明地为它创建一个默认的构造元素.(如果您不想要这种行为,您可以改用 map::at 函数.)

If it can't find one it transparently creates a default constructed element for it. (If you do not want this behaviour you can use the map::at function instead.)

您可以在此处获取 std::map 方法的完整列表:

You can get a full list of methods of std::map here:

http://en.cppreference.com/w/cpp/container/map

这是当前 C++ 标准中 map::operator[] 的文档...

Here is the documentation of map::operator[] from the current C++ standard...

  1. 效果:如果映射中没有与 x 等效的键,则将 value_type(x, T()) 插入映射中.

  1. Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

要求:key_type 应为 CopyConstructible,mapped_type 应为 DefaultConstructible.

Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.

返回:对 *this 中 x 对应的映射类型的引用.

Returns: A reference to the mapped_type corresponding to x in *this.

复杂度:对数.

T&运算符[](key_type&& x);

  1. 效果:如果映射中没有与 x 等效的键,则将 value_type(std::move(x), T()) 插入映射中.

  1. Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.

要求:mapped_type 应为 DefaultConstructible.

Requires: mapped_type shall be DefaultConstructible.

返回:对 *this 中 x 对应的映射类型的引用.

Returns: A reference to the mapped_type corresponding to x in *this.

复杂度:对数.

相关文章