Both ways lookup container
-
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;
Alternatively:
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.
-
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 astd::lower_bound
for key/value lookup can be a solution.