[英]How value of map is getting initialized as there is no assignment operator used?
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, int> m;
for (int i = 0; i < 5; i++)
m[i]++;
for (int i = 0; i < 5; i++)
cout<<m[i];
}
Output:输出:
11111 11111
Now, how come value of m[i] is getting initialized?现在,如何初始化 m[i] 的值? Shouldn't it translate to m[i]'s value incremented by 1?
它不应该转换为 m[i] 的值加 1 吗?
Shouldn't it translate to m[i]'s value incremented by 1?
它不应该转换为 m[i] 的值加 1 吗?
It is.这是。 when you do
map[key]
if key
does not exist it adds it to the map and value initializes the value that is mapped to key.当您执行
map[key]
如果key
不存在,它会将其添加到地图中,而 value 会初始化映射到 key 的值。 For an int
value initialization means zero initialization.对于
int
值初始化意味着零初始化。 So, m[i]
is 0
, and the the ++
increments it to 1
.因此,
m[i]
是0
,并且++
其增加到1
。
If you looks at the docs for std::map::operator[]
如果您查看
std::map::operator[]
的文档
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist .
返回对映射到与 key 等效的键的值的引用,如果这样的键不存在,则执行插入。
So basically m[i]
will perform an insertion if that key does not already exist, then the increment will occur with a reference to the newly inserted value.因此,基本上
m[i]
将执行插入,如果该键不存在,则增量将发生并引用新插入的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.