c++ - 将值附加到嵌套的 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
谁能告诉我我做错了什么?
解决方案
此代码示例有两个问题:
第一的:
容器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
}
}
推荐阅读
- jekyll - Zeit Now CLI 没有显示这样的文件或目录
- mysql - 从一个表中获取所有 ID 并根据它在另一个表中插入值
- python - 如何从 obj 文件在 pyOpenGL 中导入 3d 纹理
- swift - 简而言之,使用 SwiftyJSON 将对象映射到数组中
- oracle - 从 hash_value 中提取 sql_id
- loops - 如果然后循环在 AutoHotkey 之间切换桌面
- angular - 检查后表达式已更改。以前的值:'null:1561881140820'。当前值:'null:1561881140880'
- python - 如果字符出现在字典中,则“加密”字符串
- r - 使用“neuralnet”包为不同层设置不同的激活函数
- python - 在文本文件中查找字符串:添加 else 语句后继续返回 False