Building a QHash with QStringList in C++

997 Views Asked by At

In C++ I am trying to build a specialized QHash like this:

QHash<QString, QStringList> myhash;

Such that I can store this type of data:

QHash key    QStringList values
----------   ------------------
A            1
             2
             3
B            5
             6

I am having trouble with the C++ syntax to properly build the hash and how to retrieve the hash values. For example, if given B, the I wish to loop and return 5,6.

Here is my hacked attempt at the logic to append to the hash when a new key,value pair is to be added:

QHash<QString, QStringList> myhash;

key = "A";
value = "2";

if (myhash.contains(key) ) {
    QStringList mylist = myhash.value(key);    
    mylist.append(value);    
} else {
    QStringList mylist;
    mylist.append(value);
    myhash.insert( key, mylist);
}

I'm unsure if this works, since I haven't been able to create the retrieve looping logic for the myhash.

Can anyone help me build and retrieve the data from such a QHash?

1

There are 1 best solutions below

0
On

I think all you need to do to add a value to a QStringList in your QHash is:

QStringList & mylist = myhash[key];  // will create and insert an empty QStringList if necessary
mylist.append(value);