Sobes.tech
Junior — Middle

Can you explain the advantages and disadvantages of using std::unordered_map in C++?

sobes.tech AI

Answer from AI

std::unordered_map is a container in C++ that implements a hash table for storing key-value pairs.

Advantages:

  • Fast access to elements by key on average in amortized O(1) time.
  • Well-suited when the order of elements is not important, but search speed is.
  • Easy to use and standardly integrated with STL.

Disadvantages:

  • No element ordering, unlike std::map, where elements are sorted by key.
  • In the worst case (with collisions), access time can degrade to O(n).
  • Uses more memory due to storing the hash table and possible collisions.

Example usage:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> ages;
    ages["Ivan"] = 25;
    ages["Maria"] = 30;

    std::cout << "Maria's age: " << ages["Maria"] << std::endl;
    return 0;
}