我不明白这段代码中发生了什么。
映射引用声明“如果容器为空,则返回的迭代器值不应被取消引用。”
但是 some_map->begin()->second
呢?在一张空 map 上。
我认为它是无效的,但这段代码打印出“0”。谁能解释为什么?
int main()
{
map<int,int> a;
printf("%d",a.begin()->second);
return 1;
}
谢谢!
最佳答案
来自 this std::map::begin
reference
If the container is empty, the returned iterator will be equal to
end()
然后查看this std::map::end
reference :
This element acts as a placeholder; attempting to access it results in undefined behavior.
[强调我的]
您正在经历一种叫做 undefined behavior 的事情这就是关于它的全部内容。只是不要做那样愚蠢的事情。
关于c++ - ->first/second 到一个空的 map 迭代器开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48642184/