PDA

View Full Version : Multiple values per key in QMap



xander333
15th November 2010, 18:12
Hello Qt Forum :D

I recently researched about QMap a bit and I have a question.
Is it possible to make a QMap ( or any other container ) that you can assign multiple values per key?

for example:


QMap<QString, int, int, double>

wysota
15th November 2010, 18:22
Take a look at QMultiMap. You can use QVariant as the value type.

xander333
15th November 2010, 19:18
I already had a look at it, but it seemed the only difference is it doesn't overwrite existing keys with the same name?

wysota
15th November 2010, 22:42
This difference is enough to suit your needs. An alternative is this:


struct SomeStruct {
int v1;
int v2;
QString v3;
};

typedef QMap<QString,SomeStruct> MyMap;

This is a better equivalent to the code from your post but less practical in my opinion.

xander333
16th November 2010, 06:26
Thanks Wysota,

but how would I set their values?
not like insert(mymap, SomeStruct) .
Because then the variables wouldn't be initialized right?

wysota
16th November 2010, 07:30
Uninitialized variables is not a problem as you can have constructors for your stuct but it might be a good idea to provide a method for the map that allows to set each value of the struct separately. But I think the solution with multimap is better in most cases as the only "trick" you need to do there is to convert QVariant to proper types when retrieving data from the map.