Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top