Pregunta

my code is

list<int> foo;
    for (int i = 0; i < 20; i++) {
        foo.push_back(i);
    }
    for (std::list<int>::iterator it = foo.begin(); it != foo.end(); it++)
        std::cout << *it << ' ';

I want my iterator increase in 3

and the output will be:

0 3 6 9 12 15 18

instead of:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
¿Fue útil?

Solución 2

A list has a bidirectional iterator only (You can only increment or decrement the iterator via ++ or --). To advance the iterator by three you could std::advance(it, 3), but that might pass the end and lead to an infinite loop / undefined behavior.

Hence:

#include <iostream>
#include <list>

int main()
{
    std::list<int> foo;
    for (int i = 0; i < 20; i++) {
        foo.push_back(i);
    }
    std::list<int>::iterator it = foo.begin();
    while(it != foo.end()) {
        std::cout << *it << ' ';
        // Advance by three, stop at end
        for(int i = 0; i < 3 && it != foo.end(); ++i, ++it);
    }
    return 0;
}

Note: You might choose a different container supporting random access (std::array, std::vector, std::deque) instead.

Otros consejos

In a list, you cannot advance the iterator by n instantly (e.g. it+3), because it is not a random access iterator. However, you can increment the iterator 3 times: ++(++(++it))).

As pointed out in the comment, you can use std::advance(it,3) but for the list iterator it will boil down to repeatedly calling ++it 3 times.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top