Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Both ways lookup container
Resurr3ction last edited by
Hi, I need to map enum values to text in a container both ways, i.e. values with keys and keys with values. The order does not matter to me. What is the most efficient way of doing this? All Qt containers are said to be efficient only one-way, meaning looking up by key is preferable and looking up keys by values is not. My solution to this so far:
QHash<MyEnum, QString> values; QHash<QString, MyEnum> keys;
QList<MyEnum> keys; QStringList values; keys.at(values.indexOf(val)); //to get text from key values.at(keys.indexOf(enum)); //to get enum from text value
But maybe there is another solution, ideally with single container... To further explain the text representation of the enum values is translatable and exposed to the user so I cannot use the QMetaEnum for the conversion.
mcosta last edited by mcosta
I had the same requirement some time ago and I used Boost MultiIndex.
Just seen on boost web site this
The best container for that task will depend on which operations you need it to be fast.
the boost.bimap suggested by @mcosta is a good starting-point general container that is more or less what your first proposition does.
If you care most about traversal performance and the bi-directional random lookup is less important (but necessary) then something like
QVector<QPair<MyEnum, QString>>with a
std::lower_boundfor key/value lookup can be a solution.