问题描述
如果我有QVector,则可以使用基于范围的循环,使用引用并更改QVector中的对象。
If I have a QVector I can use a range based loop, use a reference and change the objects in the QVector.
但是在修改对象时需要索引的情况下,必须使用普通的for循环。但是,如何在QVector中更改对象的值呢?
But in the case where I need the index while modifying the object I have to use an ordinary for loop. But how can I then change the value of the object in the QVector?
作为解决方法,我在更改临时对象后使用了replace方法,但这有点丑陋。
As workaround I used the replace method after changing the temporary object but that is kind of ugly.
这代码是:
struct Resource {
int value = 0;
};
int main(int argc, char *argv[])
{
QVector<Resource> vector{Resource{}, Resource{}, Resource{}};
qDebug() << vector.at(0).value
<< vector.at(1).value
<< vector.at(2).value;
for(Resource &res : vector)
res.value = 1;
qDebug() << vector.at(0).value
<< vector.at(1).value
<< vector.at(2).value;
for(int i = 0; i < vector.size(); ++i) {
//Resource &res = vector.at(i); <-- won't compile: cannot convert from 'const Resource' to 'Resource &'
Resource &res = vector.value(i); //Compiles, but creates temporary Object and doesn't change the original object
res.value = i;
//vector.replace(res); <-- Workaround
}
qDebug() << vector.at(0).value
<< vector.at(1).value
<< vector.at(2).value;
}
推荐答案
使用数组下标运算符, []
。
Use the array subscript operator, []
.
Resource &res = vector[i];
或者您可以丢弃引用变量并直接访问:
or you can discard the reference variable and do a direct access:
vector[i].value = i;
此运算符返回对指定索引处的对象的非常量引用。
This operator returns a non-const reference to the object at the specified index.
这篇关于在普通的for循环中更改QVector的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!