mardi 29 décembre 2015

Changing max_load_factor() causing segfault in std::unordered_map

I have std::unordered_map which I have initialized with bucket size 100. When I change the max_load_factor, code is giving segfault while accessing the bucket_size(). I am using g++ as compiler on linux. I want to increase load factor so that elements collide.

1> Why I am getting segfault? 2> What is correct way to set max_load_factor for unordered_map? as far as I know constructor of std::unordered_map does not accept load factor as argument.

Code without setting max_load_factor, gives no problem

// 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;
}

Output

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.

Now once I introduce the code to change the max_load_factor, I get segfault.

#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;
}

Output

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

Aucun commentaire:

Enregistrer un commentaire