std::map::operator[](std::map::operator[])
问题描述
I was doing a simple map program but ended up with this question. The c++ doc says this:
Access element If k matches the key of an element in the container, the function returns a reference to its mapped value. If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).
The part I don't really get is where it says "the element is constructerd using its default constructor".
I gave it a try and made this
std::map<string, int> m;
m["toast"];
I just wanted to see what value would the mapped element of "toast" be. And it ended up being zero, but, why? does the primitive types have a default constructor? or what is happening?
The statement of "using its default constructor" is confusing. More precisely, for std::map::operator[], if the key does not exist, the inserted value will be value-initialized.
When the default allocator is used, this results in the key being copy constructed from key and the mapped value being value-initialized.
For int
, it means zero-initialization.
4) otherwise, the object is zero-initialized.
这篇关于std::map::operator[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::map::operator[]
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01