Matt
Matt

Reputation: 15

Appending a value to a nested QList

I am trying to append values to a QList inside another QList but it doesn't seem to work?

Here is a MCVE of my problem where I try to append int values:

#include <QList>
#include <QDebug>

int main(int argc, char *argv[]) {

    QList<QList<int>> my_list;

    int result;
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 4; ++j) {
            result = i * j;
            my_list.value(i).push_back(result);
            qDebug() << my_list.size() << "," << my_list.value(i).size() << " : " << my_list.value(i).value(j);
        }
    }

    return 0;
}

This yields:

Starting C:\Users\ ... \build\release\name_of_the_app.exe...
0 , 0  :  0
0 , 0  :  0
0 , 0  :  0
0 , 0  :  0
0 , 0  :  0
0 , 0  :  0
0 , 0  :  0
0 , 0  :  0
C:\Users\ ... \build\release\name_of_the_app.exe exited with code 0

Can anyone please tell me what I'm doing wrong?

Upvotes: 0

Views: 592

Answers (1)

TrebledJ
TrebledJ

Reputation: 8997

There are two issues with this code sample:

First:

The container my_list hasn't been initialised yet. The line

my_list.value(i).push_back(result);

doesn't actually push values into the container (as we might have hoped).

In your code, i is always out of bounds. (Since my_list will always have size 0.) As a result, and according to the documentation,

If the index i is out of bounds, the function returns a default-constructed value.

Since this default-constructed value isn't assigned anywhere, it will most probably be allocated on the heap and be left sitting there until destructed.

Further accesses into my_list such as qDebug() << my_list.value(i).size() will default-construct another QList (since again, i is out of bounds).

Make sure you already have QList<int> ready to push values into.

Second:

The value() method returns a const reference to the QList which does not allow modification (same for at()). If you want to push values to a QList you should use the [] instead of the value() method.

The following code does what you want:

for (int i = 0; i < 2; ++i) {
    my_list.push_back(QList<int>());   // first appends a new QList at index `i`

    for (int j = 0; j < 4; ++j) {
        result = i * j;
        my_list[i].push_back(result);  // safely retrieves QList at index `i` and adds an element
    }
}

Upvotes: 1

Related Questions