C++ STL 中 unordered_multimap bucket() 函数
unordered_multimap::bucket() 是 C++ STL 中的内置函数,其返回给定键所在的桶编号。桶的大小从0到bucket_count-1不等。
语法:
unordered_multimap_name.bucket(key)
参数: 函数接受一个必需的单一参数键,该键指定要返回其桶编号的键。
返回值: 它返回一个无符号整型,表示键所在的桶编号。
如下程序说明了上述功能:
程序1:
// C++ program to illustrate the
// unordered_multimap::bucket()
#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 });
// iterate for all elements and print its bucket number
for (auto it = sample.begin();
it != sample.end(); it++) {
cout << "The bucket number in which {"
<< it->first << ", "
<< it->second << "} is "
<< sample.bucket(it->first) << endl;
}
return 0;
}
The bucket number in which {15, 150} is 1
The bucket number in which {30, 300} is 2
The bucket number in which {20, 200} is 6
The bucket number in which {10, 100} is 3
The bucket number in which {10, 100} is 3
程序2:
// C++ program to illustrate the
// unordered_multimap::bucket()
#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' });
// iterate for all elements and print its bucket number
for (auto it = sample.begin();
it != sample.end(); it++) {
cout << "The bucket number in which {"
<< it->first << ", "
<< it->second << "} is "
<< sample.bucket(it->first) << endl;
}
return 0;
}
The bucket number in which {c, b} is 1
The bucket number in which {r, a} is 2
The bucket number in which {b, c} is 0
The bucket number in which {a, b} is 6
The bucket number in which {a, b} is 6