Sobes.tech
Junior — Middle

Can you name and describe the main types of associative containers in standard libraries?

sobes.tech AI

Answer from AI

In the C++ standard library (STL), the main associative containers are data structures that store key-value pairs and provide fast access by key. Main types:

  1. std::map — a sorted associative container, usually implemented based on a red-black tree. Keys are unique, and elements are stored in sorted order by key. Insertion, search, and deletion are O(log n).

  2. std::multimap — similar to map, but allows multiple elements with the same key.

  3. std::unordered_map — an associative container based on a hash table. Keys are unique, and insertion, search, and deletion operations are on average O(1), but the order of elements is not defined.

  4. std::unordered_multimap — like unordered_map, but allows multiple elements with the same key.

Example of using std::map:

#include <iostream>
#include <map>

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

    for (const auto& [name, age] : ages) {
        std::cout << name << ": " << age << " years\n";
    }
    return 0;
}