I am trying to understand how is iterating through a hashtable implemented. I just cannot imagine it. I am particularly interested in the speed of such iteration. For example:
QHash<int, std::string> hashTable;
...
for (auto it = hashTable.begin(); it != hashTable.end(); ++it)
std::cout << it.value() << std::endl;
Is this an O(hashTable.size()) operation?
I tried to dig in the source code, but could not find the proper definition.
Some implementations of hash tables also maintain a linked list of all entries to allow fast iteration (a so-called “linked hash-map”).
When they don’t, the only way is to iterate over all buckets of the hash table, while also iterating over the elements in each bucket.
The speed of this operation depends on the fill state of the table. When it’s very low, a lot of empty buckets need to be iterated, which wastes time. When the table is filled well, and one or more elements are in each bucket, it’s almost like iterating a linked list. On a perfect hash map where each bucket contains exactly one element, it’s like iterating an array.