tags:

views:

69

answers:

2

Assume that a program is run several times in identical fashion. In each run, the same set of objects is insert into a QHash in the same insertion order; then the objects in the QHash are iterated. The question is will the objects be iterated in the same order in each run of the program?

+2  A: 

Probably, but you can't absolutely rely on it.

QHash like QSet requires that any type used as a key provide an overload of the qHash function that converts an object into a hash code. Inside the hash, the items are ordered by hash code. Normally, this conversion into a hash code would be stable and deterministic, and so the objects would receive the same hash codes and would thus be in the same order, even between runs.

However, there's nothing to stop someone from creating a type where the output qHash depends on some value (e.g. a pointer address held within the object) that would be constant for a particular run, but not consistent between runs.

Tyler McHenry
A: 

If the qHash overloads being used are guaranteed to return the same qHash values across program runs, then is the QHash iteration order guaranteed to be the same across runs? Is there anything else about how QHash is implemented (besides relying on qHash return values) that might cause QHash iteration order to vary across program runs for the exact same set of objects (inserted in the same order)?

Ulick Malone
This should have been posted as a comment on my answer, and not an answer itself. However, the response is that the Qt docs call `QHash` "unordered", so there is no interface guarantee that the iteration order will be the same even if the insertion order and `qHash` values are. That said, if you examine the source code, you will find that it will be the same, and it's likely to remain that way because it would actually take deliberate effort to make it not work that way. So again, the answer is "in practice yes, in theory no".
Tyler McHenry