简体   繁体   中英

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?

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());

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, ie 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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM