Access Data using two keys in QMap

60 views Asked by At

I am using QMap<quint8, QString> for accessing QString data using quint8 type key. So, using a single key to access the string data.

I want to store two keys QMap<quint8, quint8, QString> to access data using two integer keys.

1

There are 1 answers

0
Numi On

I assume that what you want to implement is that someone needs both keys to access the value.

This is functionally equivalent to a single combined key composed of these two individual quint8 keys. You have two options:

  1. Put both quint8's into a custom struct and use the struct as a key:

    struct doubleIntKey{ quint8 A; quint8 B; };

    QMap<doubleIntKey, QString> myMap;

Note that this would require a hash function for doubleIntKey. Either write your own or use something like boost::hash_combine.

  1. Combine them into a single datatype that is already hashable. For example, convert each into two QStrings (one per quint8) and concatenate them. Then you could use this combined QString as a key

Personally I'd go for option 1 with boost::hash_combine. It'll be easier to implement (if you end up using a more complex schema with greater quantity/complexity of constituent keys), be more extensible and probably much faster and more memory-efficient