C++ unordered_set::max_bucket_count() 函式



C++ 的unordered_set::max_bucket_count()函式用於返回unordered_set容器由於系統和庫實現限制而持有的最大桶數。桶是容器內部雜湊表中的一個槽,元素根據其鍵的雜湊值分配到該槽中。它的編號範圍從0到bucket_count - 1。

語法

以下是std::unordered_set::max_bucket_count()函式的語法。

size_type bucket_count() const noexcept;

引數

此函式不接受任何引數。

返回值

此函式返回unordered_set中最大桶數。

示例 1

讓我們來看下面的例子,我們將演示unordered_set::max_bucket_count()函式的使用。

#include <iostream>
#include <unordered_set>
using namespace std;

int main(void){
   unordered_set<char> uSet = {'a', 'b', 'c', 'd'};
   cout << " Maximum Number of buckets = " << uSet.max_bucket_count() << endl;
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Maximum Number of buckets = 576460752303423487

示例 2

考慮下面的例子,我們將獲取最大桶數並顯示總桶數。

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

int main () {
   unordered_set<string> uSet = {"Aman","Garav", "Sunil", "Roja", "Revathi"};
   unsigned max = uSet.max_bucket_count();
   cout << "uSet has maximum: " << max << " buckets. \n"; 
   unsigned n = uSet.bucket_count();
   cout << "uSet has total number of bucket: "<< n <<" buckets. \n";
   return 0;
}

輸出

以下是上述程式碼的輸出:

uSet has maximum:2863311530 buckets. 
uSet has total number of bucket: 13 buckets. 

示例 3

在下面的例子中,我們將考慮兩個unordered_set,一個是空的,另一個包含元素,並應用unordered_set::max_bucket_count()和bucket_count()函式。

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
   unordered_set<char> uSet;
   uSet.insert({'a', 'b', 'c', 'd'});
   unordered_set<char> myUSet;
   
   unsigned max1 = uSet.max_bucket_count();
   int n1 = uSet.bucket_count();
   cout << "uSet has maximum: " <<  max1 <<  " buckets.\n";
   cout << "uSet has: " << n1 << " buckets. \n";
 
   unsigned max2 = myUSet.max_bucket_count();
   int n2 = myUSet.bucket_count();
   cout << "myUSet has maximum: " <<  max2 <<  " buckets.\n";
   cout << "myUSet has: " << n2 << " buckets. \n";
   
   return 0;
}

輸出

上述程式碼的輸出如下:

uSet has maximum: 4294967295 buckets.
uSet has: 13 buckets. 
myUSet has maximum: 4294967295 buckets.
myUSet has: 1 buckets. 
廣告