Search code examples
c++qtqmapqvector

how to change the value of elements in a QVector of QMaps


I have created a QVector of QMap and pushed some qmaps into the qvector.

QVector<QMap<QString, QString>> * x;
QMap<QString, QString> tMap;
tMap.insert("name", "jim");
tMap.insert("lname", "helpert");
x->push_back(tMap);

tMap.insert("name", "dwight");
tMap.insert("lname", "schrute");
x->push_back(tMap);

after this, I wanna change some values of x like:

for(int i=0; i<x->length(); i++){
    if(x->value(i)["name"] == "target"){
        x->value(i)["name"] = "new value";
        break;
    }
}

But changing the values of qvector doesn't work.


Solution

  • The problem is that the QVector::value function returns the value by value.

    That means it returns a copy of the value, and you modify the copy only.

    Use the normal [] operator instead to get a reference to the map:

    if((*x)[i]["name"] == "target"){
        (*x)[i]["name"] = "new value";
        break;
    }