gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:57:16 30 4
gpt4 key购买 nike

简介

我正在寻找有关 std::unordered_mapreserve 方法行为的说明。让我们与 std::vector 的情况进行对比。引用 cppreferencestd::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.

但是对应的页面为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. 是否可以进行检查以确保不执行不必要的、可能代价高昂的重新散列?例如,如果我的 map 当前的大小为 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)

关于c++ - 对 std::unordered_map::reserve 的不必要或冗余调用的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45105772/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com