unordered_set rehash() function in C++ STL
Last Updated :
23 Jun, 2022
The unordered_set::rehash() is a built-in function in C++ STL which is used to set the number of buckets in the container of unordered_set to given size or more. If size is greater than the current size of the container, then rehash is called. If it is lower than the current size, then the function has no effect on bucket count of hash. Syntax:
unordered_set_name.rehash(size_type n)
Parameter: The function accepts a mandatory parameter n which specifies the minimum number of buckets for the container. Return Value: This function doesn’t returns anything. Below programs illustrate the unordered_set::rehash() function: Program 1:
CPP
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<string> us;
us.rehash(9);
us.insert("geeks");
us.insert(" for ");
us.insert("geeks");
us.insert("users");
for ( auto it = us.begin(); it != us.end(); it++) {
cout << *it << " ";
}
cout << "\nThe bucket count is "
<< us.bucket_count();
return 0;
}
|
Output:
users for geeks
The bucket count is 11
NOTE: Here we rehash(9) which means the number of buckets in given unordered_set is 9 but instead of 9 here 11 is print, because 11 is the first prime number after the 9 that is why 11 is print instead of 9.
Program 2:
CPP
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<string> us;
us.rehash(20);
us.insert("geeks");
us.insert(" for ");
us.insert("geeks");
us.insert("users");
us.insert("are");
us.insert("experts");
us.insert("in");
us.insert("DS");
for ( auto it = us.begin(); it != us.end(); it++) {
cout << *it << " ";
}
cout << "\nThe bucket count is "
<< us.bucket_count();
return 0;
}
|
Output:
DS in experts are users for geeks
The bucket count is 23
NOTE: Here we rehash(20) which means the number of buckets in given unordered_set is 20 but instead of 20 here 23 is print, because 23 is the first prime number after the 20 that is why 23 is print instead of 20.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...