我最近偶然发现了同样的问题。这是我想出的
#include <unordered_set>
#include <iostream>
using namespace std;
int main() {
unordered_set<int> u;
int ins = 0;
for (int i=0; i<30; i++) {   // something to fill the test set
    ins += i;
    ins %= 73;
    u.insert(ins);
}
cout << "total number of buckets: " << u.bucket_count() << endl;
for(size_t b=0; b<u.bucket_count(); b++)      //showing how the set looks like
    if (u.bucket_size(b)) {
        cout << "Bucket " << b << " contains: ";
        unordered_set<int>::local_iterator lit;
        for (lit = u.begin(b);  lit != u.end(b);) {
            cout << *lit;
            if (++lit != u.end(b))
                cout << ", ";
        }
        cout << endl;
    }
cout << endl;
int r = rand() % u.bucket_count();
while (u.bucket_size(r) == 0)         // finding nonempty bucket 
    r = (r + 1) % u.bucket_count();   // modulo is here to prevent overflow
unordered_set<int>::local_iterator lit = u.begin(r);
if (u.bucket_size(r) > 1) {              // if bucket has more elements then
    int r2 = rand() % u.bucket_size(r);  // pick randomly from them
    for (int i = 0; i < r2; i++)
        lit++;
}
cout << "Randomly picked element is " << *lit << endl;
cin.ignore();
return 0;
}
现在对于重新散列问题:
- 如果您的集合正在增长,则在其元素/存储桶比率大于 1 后默认重新散列。所以我的解决方案在这里是安全的。
- 但是,如果您的集合增长然后迅速缩小,则在集合为空之前不会重新散列,因此您可能需要执行检查并最终重新散列。 - 如果 (u.load_factor() < 0.1) u.rehash(u.size()); 
这会检查集合是否至少 10% 已满,如果没有,则重新散列,以便集合的大小适合存储当前的元素数量。(通常新大小等于大于大小的 2 的较小幂)