公共成員函式
<unordered_map>

std::unordered_map::bucket

size_type bucket ( const key_type& k ) const;
定位元素的桶
返回鍵值為 k 的元素所在的桶編號。

桶是容器內部雜湊表的一個槽,元素根據其鍵的雜湊值被分配到其中。桶的編號從 0 到0(bucket_count-1).

可以透過 unordered_map::beginunordered_map::end 返回的範圍迭代器來訪問桶中的單個元素。

引數

k
要查詢其桶的鍵。
成員型別key_type是容器中元素的鍵的型別,在 unordered_map 中定義為其第一個模板引數的別名().

返回值

k 對應的桶的順序號。

成員型別size_type是一種無符號整型型別。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// unordered_map::bucket
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,std::string> mymap = {
    {"us","United States"},
    {"uk","United Kingdom"},
    {"fr","France"},
    {"de","Germany"}
  };

  for (auto& x: mymap) {
    std::cout << "Element [" << x.first << ":" << x.second << "]";
    std::cout << " is in bucket #" << mymap.bucket (x.first) << std::endl;
  }

  return 0;
}

可能的輸出
Element [us:United States] is in bucket #1
Element [de:Germany] is in bucket #2
Element [fr:France] is in bucket #2
Element [uk:United Kingdom] is in bucket #4


複雜度

常量。

迭代器有效性

沒有變化。

另見