0

I want to get a random pair with number n from my QHash.

Now I do it this way:

QHash<QString,QString>::iterator iterator = dictionary.begin();
iterator+= n;
question->setText(iterator.key());

But this seems just ridiculous... There must be a normal way. Can you help me please? I've read the whole entire man-page for QHash already

Kolyunya
  • 5,973
  • 7
  • 46
  • 81

1 Answers1

1

QHash doesn't offer random selection. If you have to perform this operation often, then copy (pointers to) the keys() of the hash table into a vector or QVector, get a random index into that and use the key to look up the value in the QHash.

Depending on what else you use the QHash for, you might want to convert it to a vector of pairs at some point and just use that for random selection.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • I need to store a 2-language dictionary in it. Seems like it's nice to store it sorted, right? I will need to do 2 operations. 1 - Get a random pair. 2 - Check if there is value-key pair in it. What do you advise to use? Maybe a `QMap`? – Kolyunya Oct 27 '12 at 17:45
  • @Kolyunya: do you regularly insert items into the `QHash`, or is it fixed at some point? – Fred Foo Oct 27 '12 at 17:47
  • It's definitely fixed. It's formed only once. – Kolyunya Oct 27 '12 at 17:48
  • @Kolyunya: then you can store the key-value pairs in a `vector` when input is done, sort the vector and use binary search to look up keys. – Fred Foo Oct 27 '12 at 17:53
  • Thanks in advance! OFFTOPIC: I'm very new to Qt and it seems me a nice lib, thus I wonder why `C` questions here have 20 times more views and answers than `Qt`. It is so unpopular here? – Kolyunya Oct 27 '12 at 17:57
  • 1
    @Kolyunya: I wouldn't be surprised if C is much more popular than Qt all-round, because it's much more broadly applicable and widely taught in colleges. – Fred Foo Oct 27 '12 at 18:27