shrink_to_fit() 用于无序容器?

shrink_to_fit() for unordered containers?

我想知道两件事...一旦容器已装满并且您知道不会有任何新项目,以类似于 shrink_to_fit() 的方式调整无序容器的大小是否有意义添加到它?这可能不是您通常想要做的事情,因为我猜这些桶只是指针大小。所以...无论如何在大多数情况下调整大小不会赢得很多 space ..或者会有吗?

其次……那个功能是什么 rehash(<bucketcount>)。但是对于无序容器,是否也有类似于 shrink_to_fit 的函数,可以删除所有空桶并相应地重新散列容器?

您想看load_factor

只有

void max_load_factor( float ml );

而不是 min_load_factor,因此您无法获得想要的东西,除非将元素移到新容器中。

decltype(orig) shrunk(std::make_move_iterator(orig.begin()),
        std::make_move_iterator(orig.end());

您可以使用

my_container.rehash(0);

缩小负载系数。

例如 unordered_set (https://en.cppreference.com/w/cpp/container/unordered_set/rehash) 的文档说:

Sets the number of buckets to count and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. If the new number of buckets makes load factor more than maximum load factor (count < size() / max_load_factor()), then the new number of buckets is at least size() / max_load_factor().