Open In App

unordered_map rehash in C++ STL

The std::unordered_map::rehash() is a built in function C++ STL which sets the number of buckets in container to n or more. Syntax 

void rehash( size_type s );

Parameters : It takes New number of buckets into the container. Return type : Its return type is none. 



Example-1: 




// C++ code to illustrate the method
// unordered_map rehash
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    unordered_map<char, int> sample;
 
    // Map initialization
    sample = { { 'a', 2 }, { 'b', 4 }, { 'c', 6 } };
 
    cout << " Size of container : " << sample.size() << endl;
    cout << " Initial bucket count : " << sample.bucket_count() << endl;
 
    // changing rehash
 
    sample.rehash(30);
    cout << " Size of container : " << sample.size() << endl;
    cout << " Now bucket count is :  " << sample.bucket_count() << endl;
    return 0;
}

Output:

Size of container : 3
 Initial bucket count : 5
 Size of container : 3
 Now bucket count is :  31

Example-2: 




// C++ code to illustrate the method
// unordered_map rehash
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
    unordered_map<int, int> sample;
 
    // Map initialization
    sample = { { 2, 2 }, { 3, 4 }, { 4, 6 }, { 5, 8 } };
 
    cout << " Size of container : " << sample.size() << endl;
    cout << " Initial bucket count : " << sample.bucket_count() << endl;
 
    // changing rehash
 
    sample.rehash(20);
    cout << " Size of container : " << sample.size() << endl;
    cout << " Now bucket count is :  " << sample.bucket_count() << endl;
    return 0;
}

Output:
Size of container : 4
 Initial bucket count : 7
 Size of container : 4
 Now bucket count is :  23

Article Tags :
C++