gpt4 book ai didi

c++ - std::unordered_map::reserve 是否保证只要映射中的元素较少就不会发生内存分配?

转载 作者:行者123 更新时间:2023-12-03 06:49:44 28 4
gpt4 key购买 nike

如果我将 std::unordered_map::reserve 与参数 n 一起使用,只要插入到映射中的元素少于 n 个,插入到映射中是否能保证不会导致堆分配?

最佳答案

标准中似乎没有这样的保证。
此外,如果您查看一个实现 - 引用 gcc ( ) 附带的 header :

In terms of Standard containers the hashtable is like theaggregation of:

  • std::forward_list<_Node> containing the elements
  • std::vector<std::forward_list<_Node>::iterator> representing the buckets

Reserve 确保您有适当数量的桶,它适本地调整 vector 的大小。所以至少不会有更多的新桶分配。但是存储桶是内部链接的列表,将元素插入其中必须分配一个新的 _Node。
所以总的来说:不,即使在保留了适当的容量后,无序映射也可能(在 gcc 的情况下 )分配堆内存。

关于c++ - std::unordered_map::reserve 是否保证只要映射中的元素较少就不会发生内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63723367/

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