2

If I have a QVector I can use a range based loop, use a reference and change the objects in the 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?

As workaround I used the replace method after changing the temporary object but that is kind of ugly.

This is the code:

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

2 回答 2

4

使用数组下标运算符[].

Resource &res = vector[i];

或者您可以丢弃引用变量并直接访问:

vector[i].value = i;

此运算符返回对指定索引处对象的非常量引用。

于 2015-10-06T14:26:17.473 回答
2

您可以使用T & QVector::operator[](int i), 因为它将索引位置的项目i作为可修改的引用返回。但是您const T & QVector::at(int i) const现在正在使用(即在这两种情况下您都有参考,但如果operator[]它不是恒定的)。

因此,您可以执行以下操作:

for(int i = 0; i < vector.size(); ++i)
  vector[i].value = i;
于 2015-10-06T14:26:52.300 回答