gpt4 book ai didi

c++ - std::map::rend() 返回数组的第一个元素,而不是之前的元素

转载 作者:太空狗 更新时间:2023-10-29 20:16:11 26 4
gpt4 key购买 nike

我正在尝试反向迭代 std::map,遵循以下代码:http://www.cplusplus.com/reference/stl/map/rend/它说:

rend() returns a reverse iterator referring to the element right before the first element in the map container, which is considered its reverse end.

Notice that rend does not refer to the same element as begin, but to the element right before it.

map<float,int> m;
m.insert(pair<float,int>(.1,0));
m.insert(pair<float,int>(.4,5));
map<float,int>::reverse_iterator rend=m.rend();
map<float,int>::iterator begin=m.begin();

当我运行它时,rend 和 begin 都指向 m 的第一个元素 (.1,0),但根据上面的通知,显然不应该。我觉得我犯了一些非常明显的错误,但我不知道它可能是什么。

(C++,MSVC2010)

最佳答案

我相信您遗漏的一点是,如果您使用调试器检查这些值,则 rend()begin() 返回的值将 包含相同的值。但是,迭代器类型的 operator* 成员仍然可以让您访问不同的对象。

技术细节:rend() 返回的值不能指向 begin() 之前,因为那是无效的。因此决定 rend() 应该包含 begin() 的值,并且所有其他反向迭代器进一步移动一个位置。 operator* 对此进行补偿并访问正确的元素。

24.5.1 反向迭代器的第一段说:

Class template reverse_iterator is an iterator adaptor that iterates from the end of the sequence defined by its underlying iterator to the beginning of that sequence. The fundamental relation between a reverse iterator and its corresponding iterator i is established by the identity:
&*(reverse_iterator(i)) == &*(i - 1).

关于c++ - std::map::rend() 返回数组的第一个元素,而不是之前的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10261705/

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