c++ - ->first/second 到一个空的 map 迭代器开始

标签 c++ iterator


我不明白这段代码中发生了什么。
映射引用声明“如果容器为空,则返回的迭代器值不应被取消引用。”
但是 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/

相关文章:

c++ - 用 C++ 编写 XML 的好方法是什么?

c++ - 了解函数是否在运行时获取引用或值

c++ - find_if 找到一个不等于某物的元素

c++ - 如何在 C++ 中生成特定的迭代器

c++ - 使用基本数据类型计算 C++ 中的阶乘项

c++ - 递归函数 C++

c++ - 如何为c++代码找到对应的程序集

jQuery 中的 PHP 连接 $i

c++ - 使用另一个 vector 迭代一个 vector 的特定元素

arrays - Swift 中带有数组的 For-In 循环中迭代器元素的可变性