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?
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.
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
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.
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
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
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With