Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advancing a list iterator

Tags:

c++

loops

list

Is there any way of starting the index of the second for loop to (i+1)? I tried mucking with advance but if I insert it in the for loop it will advance by 1 for every iteration. I just want it to start at (i+1) and carry on.

for (list< list<string> >::const_iterator i = l.begin(); i != l.end(); i++)
    if (i -> front() == s)
        for(list<string>::const_iterator j = i ->begin(); j != i -> end(); j++)
            cout << *j << "  ";
  • j = i -> begin() + 1 threw an error.
  • j = advance(i, 1) -> begin() failed as well.
like image 556
Kevin Zakka Avatar asked Jan 18 '26 22:01

Kevin Zakka


1 Answers

You can use std::next which does not modify its argument

std::list<std::string>::const_iterator j = std::next(i->begin());

or deduce the iterator type with auto

auto j = std::next(i->begin());

Use std::advance when you want to advance a given iterator by some distance. advance(it, n) achieves it += n, while next(it, n) achieves it + n. Advance doesn't return anything, it does its work on its input.

operator+ with an integral won't work for std::list because it has a BidirectionalIterator, the binary plus is only supported by RandomAccessIterator.

These utilities provided by <iterator> use some template magic to figure out the best way to advance an iterator. In short, if you give next something that doesn't have an operator+, it will make a copy and repeatedly call ++ N times.

like image 164
Ryan Haining Avatar answered Jan 20 '26 13:01

Ryan Haining



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!