Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update the value of QHash for a specific key?

Tags:

c++

qt

qtcore

qhash

I am using QHash in C++ to store some simple key and value pairs. In my case the key is an integer, so is the value. To add a new key/value pair to the hash, this is my syntax:

QHash<int, int> myhash;
int key = 5;
int value = 87;

myhash.insert(key,value);

qDebug() << "key 5 value = " << myhash.value(5);   // outputs 87

How can I update an existing key-value par? What is the syntax?

like image 219
panofish Avatar asked Oct 24 '13 19:10

panofish


2 Answers

T & QHash::operator[](const Key & key) Returns the value associated with the key as a modifiable reference.

You can do the following:

myhash[5] = 88;

According to the documentation if the key is not present, a default value is constructed and returned. This means that depending on the scenario you might want to consider first making sure that the key is actually present (for example if you are iterating through the keys in a for/foreach loop and using the retrieved key to call the [] operator, you will avoid this issue) or check the retrieved value and whether it is a default one or not.

like image 59
vahancho Avatar answered Nov 13 '22 08:11

vahancho


From docs: If you call insert() with a key that already exists in the QHash, the previous value is erased. For example:

hash.insert("plenty", 100);
hash.insert("plenty", 2000);
// hash.value("plenty") == 2000

Operator[] works too in this case. But be aware in some other cases. From docs: In general, we recommend that you use contains() and value() rather than operator for looking up a key in a hash. The reason is that operator silently inserts an item into the hash if no item exists with the same key (unless the hash is const).

like image 38
I am user3179295 Avatar answered Nov 13 '22 06:11

I am user3179295