Change object of a QVector in an ordinary for loop

自古美人都是妖i 提交于 2019-12-13 07:06:28

问题


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

回答1:


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.




回答2:


You can use T & QVector::operator[](int i), because it returns the item at index position i as a modifiable reference. But you are using const T & QVector::at(int i) const now (i.e. in both cases you have a reference, but in case of operator[] it is not constant).

So, you can do something like this:

for(int i = 0; i < vector.size(); ++i)
  vector[i].value = i;


来源:https://stackoverflow.com/questions/32972390/change-object-of-a-qvector-in-an-ordinary-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!