简体   繁体   English

反向迭代器未按预期工作 C++

[英]Reverse Iterator not working as expected C++

Hey i was wondering why this code doesnt give 1 to output.嘿,我想知道为什么这段代码不给 output 1。


    vector<int> myVector{1, 2, 3, 4, 6};
    cout << *myVector.rend() << endl;

Output should be 1 but it gives random numbers. Output 应该是 1 但它给出随机数。

But in this example everything is okay.但在这个例子中,一切都很好。


    vector<int> myVector{1, 2, 3, 4, 6};
    cout << *myVector.rbegin() << endl;

Output: 6 Output:6

Thanks.谢谢。

end() points to the memory location after the last element. end()指向最后一个元素之后的 memory 位置。 Similarly, rend() points to memory location before the first element.同样, rend()指向第一个元素之前的 memory 位置。 They are supposed to be used as sentinel values ─ ie to iterate until that point is reached.它们应该用作标记值——即迭代直到达到该点。 So, to print 1, you should use:因此,要打印 1,您应该使用:

cout << *(myVector.rend()-1) << endl;

"end" iterators are really "past the end" and not dereferencable, no matter whether they're forward or reverse. “结束”迭代器实际上是“结束”并且不可取消引用,无论它们是正向还是反向。

BTW: Enable diagnostic mode for you C++ stdlib.顺便说一句:为您启用诊断模式 C++ stdlib。 It would have told you something's wrong.它会告诉你有什么问题。 How you do that depends on the compiler and stdlib.你如何做到这一点取决于编译器和标准库。

In the same way that end() gives an invalid iterator "one item after the range", rend() gives an invalid iterator "one item before the range".end()给出“范围之后的一项”的无效迭代器相同的方式, rend()给出“范围之前的一项”的无效迭代器。 So your first example outputs whatever semi-random data happens to be at that place in memory.因此,您的第一个示例输出 memory 中该位置的任何半随机数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM