简体   繁体   中英

Reverse Iterator not working as expected C++

Hey i was wondering why this code doesnt give 1 to output.


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

Output should be 1 but it gives random numbers.

But in this example everything is okay.


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

Output: 6

Thanks.

end() points to the memory location after the last element. Similarly, rend() points to memory location before the first element. They are supposed to be used as sentinel values ─ ie to iterate until that point is reached. So, to print 1, you should use:

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. 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". So your first example outputs whatever semi-random data happens to be at that place in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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