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