當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ unordered_multiset bucket_count()用法及代碼示例


unordered_multiset::bucket_count()是C++ STL中的內置函數,該函數返回unordered_multiset容器中的存儲桶總數。值區是容器內部哈希表中的一個插槽,根據其哈希值將元素分配給該插槽。

用法:

unordered_multiset_name.bucket_count()

參數:該函數不接受任何參數。


返回值:它返回一個無符號整數類型,表示桶的總數。

以下示例程序旨在說明上述函數:

示例1:

// C++ program to illustrate the 
// unordered_multiset::bucket_count() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multiset<char> sample; 
  
    // inserts element 
    sample.insert('a'); 
    sample.insert('b'); 
    sample.insert('b'); 
    sample.insert('b'); 
    sample.insert('z'); 
  
    cout << "The total count of buckets: " << sample.bucket_count(); 
  
    // prints all element bucket wise 
    for (int i = 0; i < sample.bucket_count(); i++) { 
  
        cout << "\nBucket " << i << ": "; 
  
        // if bucket is empty 
        if (sample.bucket_size(i) == 0) 
            cout << "empty"; 
  
        for (auto it = sample.cbegin(i); it != sample.cend(i); it++) 
            cout << *it << " "; 
    } 
    return 0; 
}
輸出:
The total count of buckets: 7
Bucket 0: b b b 
Bucket 1: empty
Bucket 2: empty
Bucket 3: z 
Bucket 4: empty
Bucket 5: empty
Bucket 6: a

示例2:

// C++ program to illustrate the 
// unordered_multiset::bucket_count() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multiset<char> sample; 
  
    // inserts element 
    sample.insert('a'); 
    sample.insert('b'); 
    sample.insert('b'); 
    sample.insert('b'); 
    sample.insert('z'); 
  
    cout << "The total count of buckets: " << sample.bucket_count(); 
  
    // prints all element bucket wise 
    for (int i = 0; i < sample.bucket_count(); i++) { 
  
        cout << "\nBucket " << i << ": "; 
  
        // if bucket is empty 
        if (sample.bucket_size(i) == 0) 
            cout << "empty"; 
  
        for (auto it = sample.cbegin(i); it != sample.cend(i); it++) 
            cout << *it << " "; 
    } 
    return 0; 
}
輸出:
The total count of buckets: 7
Bucket 0: b b b 
Bucket 1: empty
Bucket 2: empty
Bucket 3: z 
Bucket 4: empty
Bucket 5: empty
Bucket 6: a


相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 unordered_multiset bucket_count() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。