normaluser
normaluser

Reputation: 57

QMap values as structs

Let's say we have this sample:

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

So what I am trying to do is check if key is already there then increment the count of the struct I need.

Please advise how to do this properly.

Upvotes: 0

Views: 3626

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

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

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

Output:

before:  0
after:  10

Update:

In the case of QMap you must use the operator [] that returns the reference of the stored value:

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

Output:

before:  0
after:  1

Update:

You have to use find() to get the iterator of the first element with the key, and if you want to access an element with the same key you must increase the iterator.

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

Output:

"doc2"   0
"doc1"   1

Upvotes: 1

Related Questions