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.
value()
returns a constant value that can not be modified, instead You must use an iterator using thefind()
method:Output:
Update:
In the case of QMap you must use the operator [] that returns the reference of the stored value:
Output:
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.
Output: