If I have a function which takes a std::vector<T>::const_iterator called begin and a std::vector<T>::const_iterator called end, is it possible for me to iterate over it in a backwards direction?
UPDATE
I can’t change the function signature, which is like this:
void func(Foo::const_iterator begin, Foo::const_iterator end)
{
...
}
and called with:
func(foo.begin(), foo.end());
which I also can’t change
I may have misunderstood the question, but do you just need:
If you need an iterator that goes backwards, ipc’s answer gives you one.
In practice with
vectoryou could probably get away withwhile (begin != end--), but don’t be tempted. It’s undefined behavior to decrement an iterator in the case where it’s at the start of the vector (i.e. when it’s equal to the result ofvector::begin()).This code requires at least a BidirectionalIterator. Fortunately,
vectorhas a RandomAccessIterator, which is even better.If you genuinely only had a ForwardIterator, then you’d have to iterate over the range and store the iterator values somewhere (like a
stack), and then use them in reverse order:This code requires at least a ForwardIterator (it will not work with a mere InputIterator).