Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 469
fredoverflow Avatar asked Jan 17 '11 18:01

fredoverflow


1 Answers

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.

like image 87
Fred Larson Avatar answered Sep 22 '22 02:09

Fred Larson