gpt4 book ai didi

c++ - 为什么 unordered_map 由于 "reserve"有足够的桶时会增加大小?

转载 作者:行者123 更新时间:2023-12-03 10:04:34 25 4
gpt4 key购买 nike

考虑这个代码。我为 unordered_map 保留 6 个点并插入 6 个元素。之后,有7个桶。为什么是这样? max_load_factor 为 1,并且有足够的存储桶用于我插入的元素数量。

#include <iostream>
#include <unordered_map>
using namespace std;

int main () {
unordered_map<std::string,std::string> mymap = {
{"house","maison"},
{"apple","pomme"},
{"tree","arbre"},
{"book","livre"},
{"door","porte"},
{"grapefruit","pamplemousse"}
};

unordered_map<std::string,std::string> mymap2; // THIS ONE!!!
mymap2.reserve(6);
for (auto i:mymap) {
mymap2[i.first] = i.second;
}


std::cout << "max_load factor " << mymap2.max_load_factor() << " mymap has " << mymap2.bucket_count() << " buckets.\n";

for (unsigned i=0; i<mymap2.bucket_count(); ++i) {
cout << "bucket #" << i << " contains: ";
for (auto it = mymap2.begin(i); it!=mymap2.end(i); ++it)
cout << "[" << it->first << ":" << it->second << "] ";
cout << endl;
}

return 0;
}
输出:
max_load factor 1 mymap has 7 buckets.
bucket #0 contains:
bucket #1 contains: [book:livre]
bucket #2 contains: [tree:arbre]
bucket #3 contains: [house:maison] [grapefruit:pamplemousse]
bucket #4 contains:
bucket #5 contains: [door:porte]
bucket #6 contains: [apple:pomme]

最佳答案

cplusplus.com website给出了这个解释:

void reserve (size_type n);

Request a capacity change

Sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements.

If n is greater than the current bucket_count multiplied by the max_load_factor, the container's bucket_count is increased and a rehash is forced.

If n is lower than that, the function may have no effect.


在您声明您的 unordered_map 时变量,它有一个 bucket_count1和一个 max_load_factor1 .
那你 reserve 6大于 max_load_factor 的桶乘以 bucket_count根据这个定义,在我看来,这种行为是正确的。
我在行 17 添加在您的代码中添加以下行以显示 bucket_count之前 reserve事实上,它是 1
 std::cout << "BEFORE RESERVE max_load factor " << mymap2.max_load_factor() << " mymap has " << mymap2.bucket_count() << " buckets.\n";
显示如下:
BEFORE RESERVE max_load factor 1 mymap has 1 buckets.
预留后:
AFTER RESERVE max_load factor 1 mymap has 7 buckets.
因此,在我看来,这种行为是正常的。

关于c++ - 为什么 unordered_map 由于 "reserve"有足够的桶时会增加大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65950046/

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