更改max_load_factor()导致std :: unordered_map

时间:2015-12-29 11:19:10

标签: c++11 unordered-map

我有std::unordered_map我用存储区大小100初始化了。当我更改max_load_factor时,代码在访问bucket_size()时给出了段错误。我在linux上使用g ++作为编译器。我想增加负载系数,以便元素发生碰撞。

1>为什么我会遇到段错? 2 - ;为max_load_factor设置unordered_map的正确方法是什么?据我所知,std::unordered_map的构造函数不接受加载因子作为参数。

没有设置max_load_factor的代码,没有问题

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

using namespace std;

int main ()
{
  std::unordered_map<int, std::string> mymap(10);
  unsigned nbuckets = mymap.bucket_count();
  std::cout << "mymap has " << nbuckets << " buckets:\n";
  std::cout << "mymap load factor " << mymap.max_load_factor() << endl;

  for (unsigned i=0; i<nbuckets; ++i) {
    std::cout << "bucket #" << i << " has " << mymap.bucket_size(i) << " elements.\n";
  }
  return 0;
}

输出

$ g++ -std=c++11  map.cpp  && ./a.out
mymap has 11 buckets:
mymap load factor 1
bucket #0 has 0 elements.
bucket #1 has 0 elements.
bucket #2 has 0 elements.
bucket #3 has 0 elements.
bucket #4 has 0 elements.
bucket #5 has 0 elements.
bucket #6 has 0 elements.
bucket #7 has 0 elements.
bucket #8 has 0 elements.
bucket #9 has 0 elements.
bucket #10 has 0 elements.

现在,一旦我介绍了更改max_load_factor的代码,我就会遇到段错误。

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main ()
{
  std::unordered_map<int, std::string> mymap(10);
  unsigned nbuckets = mymap.bucket_count();
  std::cout << "mymap has " << nbuckets << " buckets:\n";
  mymap.max_load_factor(10);
  std::cout << "mymap load factor " << mymap.max_load_factor() << endl;

  for (unsigned i=0; i<nbuckets; ++i) {
    std::cout << "bucket #" << i << " has " << mymap.bucket_size(i) << " elements.\n";
  }
  return 0;
}

输出

$ g++ -std=c++11  map.cpp  && ./a.out
mymap has 11 buckets:
mymap load factor 10
bucket #0 has 0 elements.
bucket #1 has 0 elements.
bucket #2 has 0 elements.
Segmentation fault

1 个答案:

答案 0 :(得分:2)

我怀疑在max_load_factor发生变化后,无法保证容器是否会保持相同的桶数。如果是这种情况,您可能会迭代无效数量的存储桶,因为nbuckets是在代码中先前定义的。