I also ran into this same phenomenon. At first I thought it was a quirk of the cling compiler; however, upon further investigation, I found this answer: Complexity of std::unordered_set iterator traversal
Here it was suggested that the iteration is by reverse-bucket-creation order. I ran a test of my own and confirmed this hypothesis.
test.cpp
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
#include <unordered_set>
using std::unordered_set;
int main() {
unordered_set<string> stuff(10);
stuff.insert("yep");
stuff.insert("123");
stuff.insert("xyz");
stuff.insert("foo");
stuff.insert("bar");
stuff.insert("baz");
stuff.insert("abc");
for (const auto& word : stuff) {
cout << word << endl;
}
cout << "bucket count: " << stuff.bucket_count() << endl;
cout << "yep: " << stuff.bucket("yep") << endl;
cout << "123: " << stuff.bucket("123") << endl;
cout << "xyz: " << stuff.bucket("xyz") << endl;
cout << "foo: " << stuff.bucket("foo") << endl;
cout << "bar: " << stuff.bucket("bar") << endl;
cout << "baz: " << stuff.bucket("baz") << endl;
cout << "abc: " << stuff.bucket("abc") << endl;
}
% g++ -std=c++17 -o test test.cpp && ./test
abc
baz
foo
bar
xyz
123
yep
bucket count: 11
yep: 8
123: 10
xyz: 9
foo: 5
bar: 9
baz: 6
abc: 3
As the buckets are created, they (their indexex) are (likely) pushed to the front of a singly-linked list (which iterates in reverse insertion order: 3, 6, 5, 9, 10, 8.
Note: the buckets are also SLLists (and thus iterate in reverse-insertion order; this is why bar
comes before xyz
in bucket 9
below).
So the iteration happens:
3) abc
6) baz
5) foo
9) bar, xyz
10) 123
8) yep
So if you have no collisions when adding your items (and your table doesn't grow) then you will have reverse-insertion order.
But if you insert more items and the table grows (and all the items are re-inserted), then your iteration order will reflect the reverse-bucket-creation order of the re-inserted items (and my guess is the items are inserted in order of iteration; so the more you insert and the more the table grows, the obfuscated the original insertion order becomes).