.bucket()
Published Nov 4, 2024
Contribute to Docs
The .bucket()
function is part of the C++ unordered_map
container. It returns the bucket number (zero-indexed) where a specified element is located within the unordered map. Each element in the unordered map is assigned to a bucket based on its hash value, and this function helps determine which bucket a given key belongs to.
Syntax
size_type bucket(const key_type& k) const;
key
: The key whose bucket number needs to be found in the unordered map.
The function returns a size_type
value, representing the zero-indexed bucket number where the specified key is stored.
Example
In this example, the bucket()
function is used to find the bucket number for the key "banana"
in the unordered map:
#include <iostream>#include <unordered_map>int main() {std::unordered_map<std::string, int> umap;umap["apple"] = 1;umap["banana"] = 2;umap["cherry"] = 3;std::string key = "banana";std::cout << "The bucket for key '" << key << "' is: " << umap.bucket(key) << std::endl;return 0;}
The above code generates the following output:
The bucket for key 'banana' is: 4
Codebyte Example
In this Codebyte, we are using the bucket()
function to find the bucket for the key "cherry"
in the unordered map:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours