fredoverflow
fredoverflow

Reputation: 263088

iterator successor

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?

Upvotes: 8

Views: 975

Answers (1)

Fred Larson
Fred Larson

Reputation: 62053

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.

Upvotes: 14

Related Questions