Search code examples
qtc++11listiterator

Why I'm printing value out of range?


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?


Solution

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

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