Sobes.tech
Junior — Middle

What is the time complexity of searching for an element by key in std::map?

sobes.tech AI

Answer from AI

In the standard library of C++, the container std::map is implemented as a balanced binary tree (usually a red-black tree). Therefore, the operation of searching for an element by key has a time complexity of O(log n), where n is the number of elements in the container.

Example of using search:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
    auto it = myMap.find(2);
    if (it != myMap.end()) {
        std::cout << "Found element: " << it->second << std::endl;
    } else {
        std::cout << "Element not found" << std::endl;
    }
    return 0;
}