简体   繁体   中英

Reverse Iterator not working as expected

I am using a reverse iterator on a std::vector and according to the following link:

http://www.cplusplus.com/reference/stl/vector/rbegin/

myVector.rbegin() is the last element of the vector. In my case, I am actually getting the past the end iterator on rbegin() and the fist element from rend() . I would have expected rend() to give me past the end iterator and rbegin() to give me the last element in the container. Did I understand the whole thing wrong?

The following is my code, nothing special. I put a break point just after the assignments, and the above is the result I am getting in the debugger ( VecDebugCubes is a type define for a std::vector<myStructure> )

VecDebugCubes::reverse_iterator itr    = pActiveDebugCubes.rbegin();
VecDebugCubes::reverse_iterator itrEnd = pActiveDebugCubes.rend();
while (itr != itrEnd)
{
  (*itr)->printDebugValues();
  ++itr;
}

See http://www.cplusplus.com/reference/std/iterator/reverse_iterator/base/ .

Dereferencing a reverse iterator will return a different value than the one that you see it pointing to in your debugger.

past the end for rbegin() and the first element for rend() is how the iterator is supposed to work. That's why it's called a reverse iterator. It's designed such that you can use it in a for loop without having to bother about making a mistake about the start and end points of the range. You'll notice that a simple i++ can be used for the iterator, and the iterator actually iterates backward on the range. I guess all you need to know is, that that's how it is supposed to work. There's nothing wrong. It just makes your life easier since you're less likely to make a mistake while writing for(i=beginAtTheEnd to finishAtTheStart and decrement-i-in-the-same-way-as-i++) rather than having for(i=10;i>0;i--) , where you might make the mistake of putting i<0 or i>1 in the condition. This is a simplified example. You'll appreciate it more when you want to reverse iterate on a container.

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