Question about QLists



  • Hi, all -

    I've been watching some Qt tutorial videos and recently came across QLists. I added some telltales at the end, just for fun, and found the results a little surprising. Here's the code:

    #include <QCoreApplication>
    #include <QList>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QList<int> list;
        QMutableListIterator<int> iter(list); // must be mutable if you want to modify list.
    
        for (int i = 0; i < 10; i++)
        {
            list.append(i);
        }
    
        while (iter.hasNext())
        {
            qDebug() << iter.next();
        }
    
        iter.toFront();
        while(iter.hasNext())
        {
            int i = iter.next();
            if (i == 5)
            {
                iter.remove();
            }
        }
    
        // I just put this in to see the results.
        foreach (int n, list)
        {
            qDebug() << n << list.value(n) ;
        }
    
        exit(0);
        return a.exec();
    }
    

    And this is the output I get:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    0 0
    1 1
    2 2
    3 3
    4 4
    6 7
    7 8
    8 9
    9 0
    

    I'm curious about the final output line. As n = 9 (ordinal 10th), wouldn't using it as an argument to value() produce an overrun, or at least a runtime error?



  • @mzimmers said in Question about QLists:

    wouldn't using it as an argument to value() produce an overrun, or at least a runtime error?

    no, value() explicitly prevent runtime errors, it just returns a default constructed item if your index overruns, you can specify what to return from value() in case of overrun with the second parameter list.value(n,42);. at() on the other hand will cause a runtime error if your index is out of bounds.
    Ref.
    http://doc.qt.io/qt-5/qlist.html#value
    http://doc.qt.io/qt-5/qlist.html#at

    P.S.
    Did you notice 6 is missing from the output? ;)

    this:

    foreach (int n, list)
        {
            qDebug() << n << list.value(n) ;
        }
    

    doesn't really make sense



  • Thanks, VRonin. And yes, I noticed that 6 is missing from the 2nd column. I did expect that, though.

    I realize the foreach doesn't make any sense, but I was just experimenting. I'm not only new to Qt, but I'm relatively new to using a lot of the containers.

    Thanks again.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.