List of key-value pairs that can return both keys and values
-
@SpaceToon said in List of key-value pairs that can return both keys and values:
QMap<QString, QBluetoothUuid> dataMap;
Please keep in mind that a QMap (or QHash) is a ONE way container: you can only look up by key.
If you want to look up also by value, i.e. do a reverse lookup, you'll need a "bimap", and you have 2 options I guess:
- use external support for such structure, i.e. Boost Bimap
- use another QMap (or QHash) to use the device Id as key
QMap<QBluetoothUuid, QString> deviceIdMap;
Using option #2 requires that you need to maintain 2 containers at the same time, i.e. if you need to remove device Id "12345" then you need to remove as well the entry in the other container matching that device Id.
Edit: you may want to look at this Stackoverflow Q&A
-
@Pablo-J-Rogina said in List of key-value pairs that can return both keys and values:
you can only look up by key.
No, you can also look up by value, see the docs. Although it's not very optimal but the OP did not tell us how much entries he has. For a small value it's negligible.
-
@Christian-Ehrlicher said in List of key-value pairs that can return both keys and values:
No, you can also look up by value, see the docs
Could you please elaborate about that? I couldn't find it.
-
@Christian-Ehrlicher thank you for the enlightment...
It was just the habit of using key as the lookup approach.
Anyways, I guess the OP has everything at hand to solve the issue. -
Thank you both very much. I have 20 key-value-pairs, the values are constant, no more are added and none are removed or changed.
@Christian-Ehrlicher do you think, that 20 pairs are too much so that the QMap would be slow? -
Hi,
@SpaceToon said in List of key-value pairs that can return both keys and values:
Thank you both very much. I have 20 key-value-pairs, the values are constant, no more are added and none are removed or changed.
@Christian-Ehrlicher do you think, that 20 pairs are too much so that the QMap would be slow?If you are having speed issue with 20 elements then it's likely somewhere else.
What makes you think that a slowdown may happen ?
-
20 list, map or array elements are nothing if you iterate correctly.
Here are several ways to iterate through a
QMap
https://doc.qt.io/qt-5/qmap.html#details -
@SGaist Hey, because in the doc is written (for
const Key QMap::key(const T &value, const Key &defaultKey = Key()) const
):This function can be slow (linear time), because QMap's internal data structure is optimized for fast lookup by key, not by value.
Therefore I thought there could be performance issues. But I tested it and I did not recognize any performance disadvantages.
20 list, map or array elements are nothing if you iterate correctly.
Here are several ways to iterate through a QMap
Thank you too!