janr
janr

Reputation: 3694

Iterating over a QList backwards

If I execute the following code:

QList<int> l;
QList<int>::const_iterator lI;

l.append(1);
l.append(2);
l.append(3);
l.append(4);
lI = l.constEnd();

while(lI != l.constBegin()) {
  std::cout << *lI << std::endl;
  --lI;
}

I get this output:

17
4
3
2

I already solved it by using the QListIterator<int>, but I really don't get why this isn't working!

Thanks in advance ...

Upvotes: 6

Views: 10838

Answers (2)

janr
janr

Reputation: 3694

Thanks for the help, I didn't know that end() isn't pointing to the last element. Therefore, you only have to decrement before you use the node value.

while(lI != l.constBegin()) {
  --lI;
  std::cout << *lI << std::endl;
}

Upvotes: 14

user1508519
user1508519

Reputation:

Try

lI = l.constEnd() - 1;

I'm not sure if that solves your problem, but as far as I know, end iterators always point one past the end of the container.

I just wanted to address your concern in the comments. When you do this:

lI = l.constEnd();

while(lI != l.constBegin()) {
  std::cout << *lI << std::endl;
  --lI;
}

You start off the end of the container, and the loop never reaches constBegin. That's because when you decrement, lI becomes constBegin and the while loop doesn't execute. (That's why 1 is never outputted.)

But if you do:

lI = l.constBegin();

while(lI != l.constEnd()) {
  std::cout << *lI << std::endl;
  ++lI;
}

The same thing happens, except the loop terminates once it reaches constEnd. Logically it makes sense, as if constEnd didn't point past the end of the container, it would cut off and not output 4.

Upvotes: 7

Related Questions