vendredi 14 juillet 2017

Behaviour of unnecessary or redundant calls to std::unordered_map::reserve

Intro

I'm looking for clarification about the behaviour of the reserve method of std::unordered_map. Let's contrast with the case of std::vector. Quoting cppreference on std::vector::reserve,

Increase the capacity of the vector to a value that's greater or equal to new_cap. If new_cap is greater than the current capacity(), new storage is allocated, otherwise the method does nothing.

However, the corresponding page for unordered_map just says

Sets the number of buckets to the number needed to accomodate at least count elements without exceeding maximum load factor and rehashes the container, i.e. puts the elements into appropriate buckets considering that total number of buckets has changed. Effectively calls rehash(std::ceil(count / max_load_factor())).

My Question

I want to know

  1. Does the standard make any similar guarantees about std::unordered_map::reserve; and, if not
  2. Is there a check that can be done to ensure that an unnecessary, possibly costly rehash is not performed? For example, if my map currently has size count, and I'm going to increase its size to new_count, should I only call reserve if

    std::ceil(new_count / max_load_factor()) > std::ceil(count / max_load_factor())
    
    

    ?

Aucun commentaire:

Enregistrer un commentaire