6

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?

panofish
  • 7,578
  • 13
  • 55
  • 96

2 Answers2

10

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.

rbaleksandar
  • 8,713
  • 7
  • 76
  • 161
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • Thanks.. I saw that in the docs, but I didn't understand what it meant without a simple example. I wish Qt docs had more examples. Much appreciated! – panofish Oct 24 '13 at 19:41
  • @panofish, the term "modifiable reference" could hint that you can change the value. – vahancho Oct 24 '13 at 19:50
  • I guessed that, but my problem was with interpreting T & QHash::operator[](const Key & key) AS myhash[5] = 88; ... of course now in hindsight, it seems easy enough :) – panofish Oct 24 '13 at 20:48
2

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