Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

iterator

list

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?

like image 621
Mihran Hovsepyan Avatar asked Apr 13 '12 08:04

Mihran Hovsepyan


People also ask

How to advance an iterator in a list in C++?

Advancing iterator in Lists: Since, lists support bidirectional iterators, which can be incremented only by using ++ and – – operator. So, if we want to advance the iterator by more than one position, then using std::next can be extremely useful.

What is the return value of a list iterator?

Returns: the index of the element that would be returned by a subsequent call to previous, or -1 if the list iterator is at the beginning of the list Returns: the index of the element that would be returned by a subsequent call to next, or list size if the list iterator is at the end of the list

How to traverse list elements in C++ using iterator?

We can use the iterator class of Standard Template Library C++ to traverse the list elements. The syntax for this is as follows: Gives the pointer to the first node of the list. Gives the pointer to the last node of the list.

How to return the previous element of a list in Java?

Java ListIterator previous () Method 1 Syntax 2 Parameters 3 Return. The above method is used to return the previous element of the given list. 4 Throws: NoSuchElementException - If the given iteration has no such previous elements. 5 Example 1 6 Example 2 7 Example 3


2 Answers

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 
like image 126
Stephan Dollberg Avatar answered Sep 22 '22 12:09

Stephan Dollberg


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".

like image 30
jalf Avatar answered Sep 21 '22 12:09

jalf