I am wondering if using map[key] to search for a value in the map (that already exists in the map) is constant-time or logarithmic-time in C++. I know that map.find(key) is logarithmic, but if the item already exists then will it be O(1) or still O(log(n))?
Example:
m[1] = 2;
if (m[1] == 2)
...
>Solution :
Note that operator[] is not just searching for a value, it is potentially adding a new one to the map:
Effects: Equivalent to:
return try_emplace(x).first->second;
The complexity of try_emplace is the same as the complexity of emplace, and this is documented in the AssociativeContainer requirement:
a_uniq.emplace(args)[…]
Complexity: Logarithmic.
– [associative.reqmts] emplace
In general, all random access into a std::map has logarithmic complexity. The complexity of operator[] and thus emplace is not affected by whether there already exists an element in the map either; it is always logarithmic.
The only way to improve this is by using some member function which lets you provide a position, such as std::map::emplace_hint.