0

The crash can be reproduced by the below codes.

#include <vector> #include <iostream> using namespace std; int main() { vector<int> tests; tests.push_back(1); tests.erase(tests.rbegin().base()); return 0; } 

If I use the normal iterator, the erase function call will not casue crash. Does anyone know what the mechanism is? I would apprecaite a explanation.

By the way, the reason I try to use reversely iterator is that deleting an element of vector during reversely iterating does not skip iterating the element after deleted element without additional codes.

5
  • 1
    tests.rbegin().base() == tests.end(). The base() iterator is one position behind where the reverse iterator logically points to. It has to be - there's no position before the first element that rend().base() could point to otherwise. Commented Mar 17, 2020 at 16:40
  • this includes a very illustrative picture: en.cppreference.com/w/cpp/iterator/reverse_iterator Commented Mar 17, 2020 at 16:42
  • what is the interest to a call as complicated as this one?! Commented Mar 17, 2020 at 16:45
  • You may be interested in the C++ erase-remove idiom. Commented Mar 17, 2020 at 16:47
  • Thans everyone for your explanations. I know what the mechanism is. Commented Mar 17, 2020 at 16:55

1 Answer 1

0

From https://en.cppreference.com/w/cpp/iterator/reverse_iterator/base:

The base iterator refers to the element that is next (from the std::reverse_iterator::iterator_type perspective) to the element the reverse_iterator is currently pointing to. That is &*(rit.base() - 1) == &*rit.

This means, in my understanding, that you are trying to start at the last element with your reverse iterator and when you get its base you are actually accessing the element AFTER the last element. This one will obviously always be outside of range.

I hope this helps clarify. If I misunderstood something, feel free to correct me.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. I learn something. I appreciate your explanation.
Thanks you @RemyLebeau for the update on my formatting. Good for the next answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.