Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Runtime complexity of searching for value in std::map using brackets?

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)
  ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;

[map.access] p1

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading