对 std::unordered_map::reserve 的不必要或冗余调用的行为

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

简介

我正在寻找有关 std::unordered_mapreserve 方法行为的说明。我们对比一下std::vector的情况。在 std::vector::reserve

上引用 cppreference

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.

然而,unordered_map对应的页面只是说

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

我的问题

我想知道

  1. 标准是否对std::unordered_map::reserve做出类似的保证;并且,如果不是
  2. 是否可以进行检查以确保不执行不必要的、可能代价高昂的重新散列?例如,如果我的地图当前大小为 count,我打算将其大小增加到 new_count,我是否应该只调用 reserve if

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

    ?

Does the standard make any similar guarantees [reserve should do nothing if the postconditions of rehash (which it calls) are satisfied: both bucket_count() >= size() / max_load_factor() and bucket_count() >= n where n is the argument to reserve)] about std::unordered_map::reserve?

不,不是。

Is there a check that can be done to ensure that an unnecessary, possibly costly rehash is not performed?

您可以在 [...] 中检查我在上面编辑到您的问题中的后置条件,但没有内置函数可以为您执行此操作。

相关标准:§23.2.5/Table 103 [unord.req] (n3337)