I want to initialize an iterator (of arbitrary kind) with the successor of another iterator (of the same kind). The following code works with random access iterators, but it fails with forward or bidirectional iterators:
Iterator i = j + 1;
A simple workaround is:
Iterator i = j;
++i;
But that does not work as the init-stament of a for loop. I could use a function template like the following:
template <typename Iterator>
Iterator succ(Iterator it)
{
return ++it;
}
and then use it like this:
Iterator i = succ(j);
Is there anything like that in the STL or Boost, or is there an even better solution I am not aware of?
I think you're looking for next
in Boost.Utility. It also has prior
for obtaining an iterator to a previous element.
Update:
C++11 introduced std::next
and std::prev
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With