wfxr
9/14/2016 - 3:32 AM

memory-usage-of-unordered_map.cpp

// 通过load_factor获取
template <typename Key, typename T>
auto real_size1(unordered_map<Key, T> map) {
    decltype(map.size()) sz;
    if (map.max_load_factor() <= 1)
        sz = map.bucket_count();
    else
        sz = map.bucket_count() * map.max_load_factor();
    return sz;
}

// 通过bucket_size获取
template <typename Key, typename T>
auto real_size2(unordered_map<Key, T> map) {
    decltype(map.size()) sz = 0;
    for (decltype(map.bucket_count()) i = 0; i < map.bucket_count(); ++i)
        sz += map.bucket_size(i) == 0 ? 1 : map.bucket_size(i);
    return sz;
}