Ulick Malone
Ulick Malone

Reputation: 11

Is order of iteration for Qt’s QHash repeatable across multiple identical runs of a program?

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?

Upvotes: 1

Views: 850

Answers (4)

VladG
VladG

Reputation: 143

Old question, but I can get this code

QSet<QPair<int, int>> set;
set.insert(qMakePair(1, 2));
set.insert(qMakePair(3, 4));
for (QSet<QPair<int, int>>::const_iterator it = set.constBegin(); it != set.constEnd(); ++it)
{
    std::cout << it->first << ' ' << it->second << std::endl;
}

to print

1 2
3 4

or

3 4
1 2

on subsequent runs on the same Qt version. So it appears the answer to the original question is No. But can someone explain why? Is it because a different seed value is passed to qhash on each run?

Upvotes: 1

Samuel Harmer
Samuel Harmer

Reputation: 4412

To quote the documentation:

QHash is unordered, so an iterator's sequence cannot be assumed to be predictable. If ordering by key is required, use a QMap.

Upvotes: 0

Ulick Malone
Ulick Malone

Reputation: 1

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)?

Upvotes: 0

Tyler McHenry
Tyler McHenry

Reputation: 76700

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.

Upvotes: 3

Related Questions