gpt4 book ai didi

c++ - std::map::iterators post increment 的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:58 25 4
gpt4 key购买 nike

据我了解,如下程序

#include <map>

int main()
{
std::map<int,int> foo;
std::map<int,int>::iterator start = foo.begin();
while (start++ != foo.end())
;
}

应该终止,但它会使用 libstdc++ 4.7.2 无限循环。该程序表现出的行为是否正确,或者标准库中是否存在错误? operator++(int) 在迭代器上的操作属性是什么?

最佳答案

map 是空的,所以第一个 start++ 试图增加一个 end 迭代器,这是未定义的行为。来自 std::map::end() :

Returns an iterator to the element following the last element of the container. This element acts as a placeholder; attempting to access it results in undefined behavior.

即使后增量 start++ 返回 start 的原始值,在本例中为 end(),这是不合理的由于存在未定义的行为,期望循环终止。

要更正,请在递增或取消引用之前检查 start 是否等于 foo.end()

关于c++ - std::map::iterators post increment 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16718532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com