Why I'm printing value out of range?

时间:2016-04-04 17:13:21

标签: qt c++11 listiterator

Consider this code:

class Foo123
{
    QList<int> a = (QList<int>()) << 1 << 2 << 3;
    QList<int>::const_iterator it;

public:

    Foo123()
    {
        it = a.begin();
    }

    void print()
    {
        qDebug() << *it;
        while(move())
        {
            qDebug() << *it;
        }
    }


    bool move()
    {
        if(it != a.end())
        {
            ++it;
            return true;
        }

        return false;
    }
};

    Foo123 f;
    f.print();

I'm always getting an extra number in the end of printing, like that:

1
2
3
58713 // this is random, from what I can tell

I guess I'm printing a value of range but I didn't understand how. Can someone point out my mistake?

2 个答案:

答案 0 :(得分:4)

It's because you have to increment first, then test:

bool move()
    {
        ++it;
        if(it != a.end()) {
            return true;
        }

        return false;
    }

答案 1 :(得分:3)

Note that in C++11, you can use an initializer list to initialize the list (sic), and you can initialize the iterator in-place, too.

So, the whole thing, fixed, would be:

#include <QtCore>

class Foo123
{
   QList<int> a { 1, 2, 3 };
   QList<int>::const_iterator it { a.begin() };
public:
   void print()
   {
      qDebug() << *it;
      while (move()) qDebug() << *it;
   }
   bool move()
   {
      ++ it;
      return (it != a.end());
   }
};

int main() {
   Foo123 f;
   f.print();
}