Search code examples
c++iterationstdlist

Does iteration go through the whole list


Take this code:

std::list<int> intList;
for (int i = 0; i < 10; ++i) {
    intList.push_back( 1 << i );
}

std::list<int>::const_iterator iterator;
for (iterator = intList.begin(); iterator != intList.end(); ++iterator) {
    std::cout << *iterator;
}

I see how to iterate through a list. Looking at the iteration I think you skip the last item. Is this the case and if so what is the best way to solve it.


Solution

  • Actually, the last item is not skipped. The iterator pointing to intList.end()-1 points to the last item instead of intList.end() as you may be thinking.