首页 > 解决方案 > 将值附加到嵌套的 QList

问题描述

我正在尝试将值附加到QList另一个内部QList,但它似乎不起作用?

这是我的问题的 MCVE,我尝试附加 int 值:

#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;
}

这产生:

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

谁能告诉我我做错了什么?

标签: c++qtappendpush-backqlist

解决方案


此代码示例有两个问题:

第一的:

容器my_list尚未初始化。线

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

实际上并没有将值推送到容器中(正如我们所希望的那样)。

在您的代码中,i总是越界。(因为my_list总是大小为 0。)因此,根据文档

如果索引 i 超出范围,则函数返回默认构造值

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
    }
}

推荐阅读