Sobes.tech
Junior — Middle

Can you explain what a std::map container in C++ is and how it works?

sobes.tech AI

Answer from AI

std::map in C++ is an associative container that stores key-value pairs, where keys are unique and sorted in ascending order (by default). Internally, std::map is usually implemented as a balanced binary tree (e.g., red-black tree), which provides logarithmic time complexity for access, insertion, and deletion of elements.

Main features:

  • Keys are unique — you cannot add two elements with the same key.
  • Elements are automatically sorted by key.
  • Access to elements is through the key.

Example of usage:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> m;
    m[1] = "one";
    m[3] = "three";
    m[2] = "two";

    for (const auto& pair : m) {
        std::cout << pair.first << ": " << pair.second << "\n";
    }
    // Output:
    // 1: one
    // 2: two
    // 3: three
}

Thus, std::map is convenient when you need to store data with fast key-based search and keep the data sorted.