Sobes.tech
Junior — Middle

Can you explain how the std::map container works in C++?

sobes.tech AI

Answer from AI

std::map is an associative container in C++ that stores key-value pairs, ordered by key. It is usually based on a balanced tree (e.g., red-black tree), which provides logarithmic time complexity for access, insertion, and deletion of elements.

Main features of std::map:

  • Keys are unique — you cannot add two elements with the same key.
  • Elements are automatically sorted by key.
  • Access to elements is through the [] operator or the at() method.

Example 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& [key, value] : m) {
        std::cout << key << ": " << value << std::endl;
    }

    return 0;
}

The output will be sorted by key:

1: one
2: two
3: three

Thus, std::map is convenient when you need to store data with fast key-based search and also have an ordered set of elements.