UNORDERD_MAP中的存储桶计数

人气:373 发布:2022-10-16 标签: c++ heap-memory dynamic-allocation unordered-map g++4.9

问题描述

在下面给出的示例程序中(来源:http://www.cplusplus.com/reference/unordered_map/unordered_map/rehash/)

// unordered_map::rehash
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,std::string> mymap;

  mymap.rehash(20);

  mymap["house"] = "maison";
  mymap["apple"] = "pomme";
  mymap["tree"] = "arbre";
  mymap["book"] = "livre";
  mymap["door"] = "porte";
  mymap["grapefruit"] = "pamplemousse";

  std::cout << "current bucket_count: " << mymap.bucket_count() << std::endl;

  return 0;
}

输出变为:

current bucket_count: 23

为什么存储桶计数变为23? 这对堆大小有什么影响?堆分配什么时候完成?在存储桶重新散列时还是在实际插入时?当动态重新分配完成时?当使用clear()还是erase()或两者都使用时?

推荐答案

libstdc++使用的默认重新散列策略是提升到大于或等于请求数量的最小素数存储桶。23是20以上的最小素数。

676