How get next (previous) element in std::list without incrementing (decrementing) iterator?

C++ListIterator

C++ Problem Overview


Say I have an std::list<int> lst and some std::list<int>::iterator it for iterating through the list. And depended to value of the it I want to use it + 1 or it - 1 in my code. Is there some good way to do that like next(), prev() (I couldn't find such things in stl documentation)? Or should I copy the it each time and increment(decrement) the copy?

C++ Solutions


Solution 1 - C++

Yes, since C++11 there are the two methods you are looking for called std::prev and std::next. You can find them in the iterator library.

Example from cppreference.com

#include <iostream>
#include <iterator>
#include <vector>
 
int main() 
{
    std::list<int> v{ 3, 1, 4 };
 
    auto it = v.begin();
 
    auto nx = std::next(it, 2);
 
    std::cout << *it << ' ' << *nx << '\n';
}

Output:

3 4

Solution 2 - C++

Copying and incrementing/decrementing the copy is the only way it can be done.

You can write wrapper functions to hide it (and as mentioned in answers, C++11 has std::prev/std::next which do just that (and Boost defines similar functions). But they are wrappers around this "copy and increment" operation, so you don't have to worry that you're doing it "wrong".

Solution 3 - C++

A simple precanned solution are prior and next from Boost.utility. They take advantage of operator-- and operator++ but don't require you to create a temporary.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMihran HovsepyanView Question on Stackoverflow
Solution 1 - C++Stephan DollbergView Answer on Stackoverflow
Solution 2 - C++jalfView Answer on Stackoverflow
Solution 3 - C++Benjamin BannierView Answer on Stackoverflow