首页 > 解决方案 > QMap 值作为结构

问题描述

假设我们有这个样本:

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

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

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

标签: c++qtqmap

解决方案


value()返回一个无法修改的常量值,而不是您必须使用迭代器使用以下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 的情况下,您必须使用返回存储值引用的运算符 []

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

推荐阅读