C++ bucket()

xer02her0's avatar
Published Jan 5, 2026
Contribute to Docs

The bucket() method returns the index of the bucket in which a specific element is stored within an unordered_set.

This method is useful for inspecting the container’s internal hash table structure or understanding how elements are distributed across buckets.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours

Syntax

unordered_set.bucket(x);

Parameters:

  • x: The element whose bucket index is queried.

Return value:

The bucket() method returns the index of the bucket containing the specified element. If the element is not present, the returned value corresponds to the bucket where the element would be placed based on its hash value.

Example: Using bucket() to locate a specific element

In this example, bucket() is used to find the bucket index of a specific element in an unordered_set:

#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::unordered_set<std::string> benders = {"earth", "air", "water", "fire"};
// Find bucket index for a specific element
std::cout << "airbenders are in bucket: " << benders.bucket("air") << std::endl;
return 0;
}

The output for this code is:

airbenders are in bucket: 0

Note: The output may vary depending on the specific C++ implementation and hash function.

Codebyte Example: Inspecting bucket placement

In this example, each element in the set is printed along with the bucket it belongs to:

Code
Output

All contributors

Contribute to Docs

Learn C++ on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours