example4_bucket_interface.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <unordered_set>
#include <string>

int main() {
    std::unordered_set<std::string> words = {
        "apple", "banana", "cherry", "date", "elderberry",
        "fig", "grape", "honeydew", "imbe", "jackfruit"
    };

    // Print bucket information
    std::cout << "Bucket count: " << words.bucket_count() << std::endl;
    std::cout << "Max bucket count: " << words.max_bucket_count() << std::endl;
    std::cout << "Load factor: " << words.load_factor() << std::endl;
    std::cout << "Max load factor: " << words.max_load_factor() << std::endl;

    // Print contents of each bucket
    for (size_t i = 0; i < words.bucket_count(); ++i) {
        std::cout << "Bucket " << i << " contains:";
        for (auto it = words.begin(i); it != words.end(i); ++it) {
            std::cout << " " << *it;
        }
        std::cout << std::endl;
    }

    // Find which bucket an element is in
    std::string search = "grape";
    size_t bucket = words.bucket(search);
    std::cout << "'" << search << "' is in bucket " << bucket << std::endl;

    // Rehash the container
    std::cout << "\nRehashing to 20 buckets..." << std::endl;
    words.rehash(20);
    std::cout << "New bucket count: " << words.bucket_count() << std::endl;

    return 0;
}
Back to std_unordered_set