iterator successor

2019-06-17 07:54发布

问题:

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?

回答1:

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.