如何更改 QMaps 的 QVector 中元素的值

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

我创建了 QMap 的 QVector 并将一些 qmap 推入 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);

在此之后,我想更改 x 的一些值,例如:

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

但是更改 qvector 的值不起作用。

问题是QVector::value函数returns值by值.

意思是returns一个copy的值,你修改的只是副本。

使用正常的 [] operator 来获取对地图的引用:

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