There is something that I can't quite get my head around with bidirectional iterators.
Going forward through the collection is ok:
auto it = set.begin();
while (it != set.end())
{
// Do something
it++;
}
end()
is the element after the last element. So let's say I want to go in reverse using the same iterator from the end:
if(it == set.end())
{
it--; // Now points to last element
}
while(it != set.begin())
{
// Do something
it--;
}
But this last loop is flawed because begin()
is the first element and we want to include it in processing. So how do we iterate back to (and including) the first element with a bidirectional iterator?
To provide context ...
The user iterates forward one by one. So they might be on the end()
or any element before the end. Then, they decide they want to go backwards. Thus the sanity check since if we are at the end we must decrement by one. Now the user goes backwards one by one. Until they reach the first element.
I asked a similar question yesterday but deleted it since I did not grasp some of the concepts which I now have corrected for forward iteration.