Consider this code. I reserve 6 spots for an unordered_map and insert 6 elements. Afterwards, there are 7 buckets. Why is this? The max_load_factor is 1 and there are enough buckets for the number of elements I insert.
#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;
}
Output:
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]