QMap 值作为结构

QMap values as structs

假设我们有这个样本:

struct test
{
    QString name;
    int count = 0;
};

QMap<QString,test> map;
test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);

test test2;
test2.name = "doc2";

map.insertMulti("pen",test2);

if(map.contains("pen"))
{
    map.value("pen",test1).count++; // Here goes the error
  //map["pen"].count++; //works but increments count of last inserted struct
}

foreach (test value, map) {
    qDebug() << value.name << " " << value.count;
}

所以我要做的是检查密钥是否已经存在,然后增加我需要的结构的数量。

请告知如何正确执行此操作。

value() returns a constant value that can not be modified, instead You must use an iterator using the find()方法:

struct Test{
    QString name;
    int count = 0;
};

QMultiMap<QString, Test> map;
Test test;
test.name = "doc1";
map.insert("pen", test);

if(map.contains("pen")){
    qDebug() << "before: " << map.value("pen").count;
    QMultiMap<QString, Test>::iterator it = map.find("pen");
    it->count += 10;
    qDebug() << "after: " << map.value("pen").count;
}

输出:

before:  0
after:  10

更新:

在 QMap 的情况下,你必须使用 operator [] 即 returns 存储值的引用:

struct Test{
    QString name;
    int count = 0;
};

QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);

Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);

if(map.contains("pen")){
    qDebug() << "before: " << map.value("pen").count;
    map["pen"].count++;
    qDebug() << "after: " << map.value("pen").count;
}

输出:

before:  0
after:  1

更新:

您必须使用 find() 来获取具有该键的第一个元素的迭代器,如果您想访问具有相同键的元素,您必须增加迭代器。

struct Test{
    QString name;
    int count = 0;
};

QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);

Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);

if(map.contains("pen")){
    // get the first item with the key
    QMap<QString, Test>::iterator it = map.find("pen");
    // the next element
    it++;
    // update value
    it->count++;
}

for(const Test & value: map){
    qDebug() << value.name << " " << value.count;
}

输出:

"doc2"   0
"doc1"   1