Hashing and std::hash

When to Use Hash Tables

In what scenarios are hash tables a good choice compared to other data structures?

Abstract art representing computer programming

Hash tables are a good choice in scenarios where you need fast lookups, insertions, and deletions based on a key. They provide constant-time O(1) average-case complexity for these operations, making them efficient for large datasets.

Consider using hash tables when:

  1. You have a large amount of data and need to perform frequent lookups based on a unique key.
  2. You want to associate values with keys and retrieve them quickly.
  3. You don't need to maintain a specific order of elements.

For example, if you're building a phone book application where you want to store and retrieve contact information based on a person's name, a hash table would be a suitable choice. The name can serve as the key, and the associated contact details can be stored as the value.

#include <iostream>
#include <string>
#include <unordered_map>

int main() {
  std::unordered_map<
    std::string, std::string> phoneBook;

  // Adding entries to the phone book
  phoneBook["John"] = "123-456-7890";
  phoneBook["Alice"] = "987-654-3210";

  // Retrieving a phone number
  std::string name = "John";
  auto it = phoneBook.find(name);
  if (it != phoneBook.end()) {
    std::cout << "Phone number of " << name
      << ": " << it->second << '\n';
  } else {
    std::cout << "Contact not found.\n";
  }
}
Phone number of John: 123-456-7890

However, if you need to maintain a sorted order of elements or perform range queries, other data structures like balanced binary search trees (e.g., std::map) might be more appropriate.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved