gpt4 book ai didi

C++ rend() 指向与 rbegin() 相同的元素

转载 作者:太空宇宙 更新时间:2023-11-04 13:12:42 27 4
gpt4 key购买 nike

运行下面的代码,我希望看到测试 1 的第 4 个值的不同地址(与值 1 和 3 不同)。这表明 rend() 与 rbegin() 相同??我也不希望循环经历第二次迭代并出现段错误。

知道我做错了什么吗?

map<unsigned long, int*> newMap;
newMap[13] = new int(1340);
cout << "test 1:" << endl;
cout << &(*(newMap.begin())) << endl;
cout << &(*(newMap.end())) << endl;
cout << &(*(newMap.rbegin())) << endl;
cout << &(*(newMap.rend())) << endl;
cout << "test 2:" << endl;
for(map<unsigned long, int*>::reverse_iterator it=newMap.rbegin();it!=newMap.rend();){
cout << "next iteration" << endl;
map<unsigned long, int*>::reverse_iterator entry = it;
it++;
delete entry->second;
newMap.erase(entry->first);
}

输出:

test 1:
0x2299050
0x7fffcd574908
0x2299050
0x2299050
test 2:
next iteration
next iteration
*** glibc detected *** ./foo: double free or corruption (fasttop): 0x0000000002299030 ***

编辑:这是一个更新/简化的版本,仍然存在同样的问题(仅限测试 2);这不会导致段错误,因为它没有使用指针,但仍会经历两次循环:

map<int, int> newMap;
newMap[13] = 1340;
cout << "test 2:" << endl;
for(map<int, int>::reverse_iterator it=newMap.rbegin();it!=newMap.rend();){
cout << "next iteration" << endl;
int index = it->first;
int value = it->second;
it++;
newMap.erase(index);
}

最佳答案

在测试 1 中,您取消引用尾后迭代器。正如 ArchbishopOfBanterbury 在评论中提到的,其结果是不确定的。

在测试 2 中,您通过删除 it.base() 指向的元素使 it 无效。 std::reverse_iterator持有指向下一个元素的迭代器(因此 newMap.rbegin() 持有等于 newMap.end()newMap.rend() 的迭代器> 持有等于 newMap.begin() 的迭代器。

当您递增it时,它等于newMap.rend(),这意味着it.base()等于newMap.begin()。然后删除 it.base() 引用的元素,这会使 it.base() 无效,从而使 it 也无效。由于 it 现在无效,因此将它与 newMap.rend() 进行比较不起作用。

关于C++ rend() 指向与 rbegin() 相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984745/

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