QHash value result when key is not in hash
-
Looking at the documentation for QHash, it says that for some reason it will
construct a default object when the key doesn't correspond to an item in the hash.
But... what if I really just want it to return nullptr?
Do I need to use a different container for that behavior? -
@Publicnamer Do you mean operator[]?
Simply use https://doc.qt.io/qt-5/qhash.html#value-1 -
@jsulm
Notice that it says:If the hash contains no item with the key, the function inserts a default-constructed value into the hash with the key, and returns a reference to it. If the hash contains multiple items with the key, this function returns a reference to the most recently inserted value.
I want it to return nullptr when the item with my key isn't in the hash.
-
@Publicnamer Please spend a bit more time to read documentation properly...
-
@Publicnamer
Although what @jsulm and @SGaist say about drawing your attention to const T QHash::value(const Key &key, const T &defaultValue) const is correct, it seems to me there is something wrong in your question.If you want to "return
nullptr
" that must mean your value type is a pointer, e.g.QHash<QString, Something*>
, notQHash<QString, Something>
. And if that is so the default constructed value (for const T QHash::value(const Key &key) const) should already benullptr
. If your hash is in factQHash<QString, Something>
you won't be able to returnnullptr
, it is not type-compatible.Is that not your case? If I am incorrect here I should be obliged if @jsulm or @SGaist corrects me.
P.S.
Be sure you use one of theseQHash::value()
methods, not the[]
operator. The former return a value when not found but do not insert a new key-value into the hash, while the latter actually inserts a new key-value into the hash. -
@Publicnamer said in QHash value result when key is not in hash:
If the hash contains no item with the key, the function inserts a default-constructed value into the hash with the key, and returns a reference to it. If the hash contains multiple items with the key, this function returns a reference to the most recently inserted value.
This is from https://doc.qt.io/qt-5/qhash.html#operator-5b-5d NOT from https://doc.qt.io/qt-5/qhash.html#value-1 !