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

panofish picture panofish · Oct 24, 2013 · Viewed 8.9k times · Source

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?

Answer

vahancho picture vahancho · Oct 24, 2013

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.