'shrink_to_fit() for unordered containers?
I am wondering two things... Does it make any sense to resize an unordered containers in a manner similar to shrink_to_fit()
once the container has been filled and you know there won't be any new items added to it? Probably this is not something you normally want to do, as the buckets are only about pointer size I guess. So... There would not be a lot of space to be won in resizing in most cases anyway.. or would there?
Secondly... what would that function There is rehash(<bucketcount>)
. But is there also a function similar to shrink_to_fit
for unordered containers that remove all empty buckets and rehashes the container accordingly?
Solution 1:[1]
You want to look at load_factor
.
There's only
void max_load_factor( float ml );
and not min_load_factor
, so you can't have what you're looking for, except by moving the elements into a new container.
decltype(orig) shrunk(std::make_move_iterator(orig.begin()),
std::make_move_iterator(orig.end());
Solution 2:[2]
You can use
my_container.rehash(0);
to shrink the load factor.
For example the documentation for unordered_set (https://en.cppreference.com/w/cpp/container/unordered_set/rehash) says:
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().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jarod42 |
Solution 2 | Hugo Walter |