When we are iterating in reverse direction, I see that most people use the following structure:
for (auto it = vec.rbegin(); it != vec.rend(); it++)
{
// block of code //
}
But for a long time, I have a doubt about using this, and I want to know why the following code does not work.
As we know, the last element will have the highest index than any element index in the array, and the array is going to take contiguous memory.
My primary doubt is when iterating backwards, why shouldn't we use it--?
I want the reason why the following code is not going to work. I am running the loop from rbegin, that is the last element, and I am going until the first element. I am decrementing it by one in every iteration.
for (auto it = vec.rbegin(); it >= vec.begin(); it--)
{
cout << *it << endl;
}
Even the below code is not working, why?
for(auto it = vec.rbegin(); it >= vec.begin(); it++)
{
cout << *it << endl;
}
First of all, in the given codes, the for loop's conditions are making issue due to type-mismatch.
The
vec.rbegin()gives thestd::vector::reverse_iterator, and thevec.begin()gives thestd::vector::iterator; those are different types and can not be compared. Hence, you get compiler errors in those places.See the following reference picture from
std::reverse_iteratorWhen you use
rbegin(), you start from the last element. In order to advance further (like every iterator implementation) it uses theoperator++. Advance here means, iterating backwards direction, because the starting point is the last element. Therefore, you should be usingit++or++itinstead.For the last for loop example, however, there is only a type-mismatch issue. Using ✱
std::reverse_iterator::base(), you could get/ convert the reverse iterator to the corresponding base iterator, and it can be compared with thevec.begin().That means the following change will make it work:
See a demo
Side Note: