Reputation: 2042
I am attempting to write a two-pass algorithm incorporating some legacy code. I want to move through a particular container twice, once in order and once in reverse order. Obviously, my first thought was to use an iterator
and a reverse_iterator
, but strangely the designers of the container class I'm using did not see fit to define a working reverse_iterator
for the container (reverse_iterators
here cannot be dereferenced like iterators
can be). I already have an algorithm that requires a reverse_iterator
.
My thought is to use the first pass iterator for the first part of the algorithm, and as I perform the algorithm push_front
the items into a new container, then iterate through the new container. This will take up memory, which isn't critical in my application, but made me wonder: are there any cleaner alternatives to reverse_iterators
in C++, or should I take the time to rework my algorithm using only forward iterators
?
Upvotes: 4
Views: 853
Reputation: 355307
If you need to iterate over the elements of a container in reverse order, you don't necessarily need to use a reverse iterator.
If the container has bidirectional iterators, then you can use ordinary iterators and use --it
to iterate from end()
to begin()
instead of using ++it
to iterate from begin()
to end()
.
Since this is a bit tricky, you can use the std::reverse_iterator
wrapper to convert an ordinary iterator into a reverse iterator (this basically swaps ++
and --
and encapsulates the trickery required to get this to work).
If the container doesn't have bidirectional iterators then that means it's impossible to iterate over the elements of the container in reverse order, in which case you would need either to rewrite your algorithm or to use a different container.
Any container that has bidirectional iterators, it should provide reverse iterator functionality; this is part of the STL and C++ Standard Library "Container" concept.
Upvotes: 5