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


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

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

用法:

unordered_multimap_name.bucket_count()

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


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

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

示例1:

// C++ program to illustrate the 
// unordered_multimap::bucket_count()  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multimap<int, int> sample; 
  
    // inserts key and element 
    sample.insert({ 10, 100 }); 
    sample.insert({ 10, 100 }); 
    sample.insert({ 20, 200 }); 
    sample.insert({ 30, 300 }); 
    sample.insert({ 15, 150 }); 
  
    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->first << ", " 
                 << it->second << "}, "; 
    } 
    return 0; 
}
輸出:
The total count of buckets: 7
Bucket 0: empty
Bucket 1: {15, 150}, 
Bucket 2: {30, 300}, 
Bucket 3: {10, 100}, {10, 100}, 
Bucket 4: empty
Bucket 5: empty
Bucket 6: {20, 200},

示例2:

// C++ program to illustrate the 
// unordered_multimap::bucket_count()  
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multimap<char, char> sample; 
  
    // inserts key and element 
    sample.insert({ 'a', 'b' }); 
    sample.insert({ 'a', 'b' }); 
    sample.insert({ 'b', 'c' }); 
    sample.insert({ 'r', 'a' }); 
    sample.insert({ 'c', 'b' }); 
  
    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->first << ", " 
                 << it->second << "}, "; 
    } 
    return 0; 
}
輸出:
The total count of buckets: 7
Bucket 0: {b, c}, 
Bucket 1: {c, b}, 
Bucket 2: {r, a}, 
Bucket 3: empty
Bucket 4: empty
Bucket 5: empty
Bucket 6: {a, b}, {a, b},


相關用法


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