Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity for a clear function is std::map according to big O?

What is the time complexity for a clear function is std::map?
Would I be right in saying that it is O(1)?

like image 976
smallB Avatar asked Nov 16 '25 03:11

smallB


2 Answers

The Standard says in [associative.reqmts]/8 Table 102:

a.clear() <=> a.erase(a.begin(), a.end()) linear in a.size()

So it is actually mandated to be O(N).


EDIT: summing up the various bits.

To remove a node, a map does two operation:

  1. Call the allocator destroy method to destroy the element
  2. Call the allocator deallocate method to deallocate the memory occupied by the node

The former can be elided in code (checking for is_trivially_destructible), and actually it is generally done in vector for example. The latter is unfortunately trickier, and no trait exists, so we must rely on the optimizer.

Unfortunately, even if by inlining the optimizer could completely remove the destroy and deallocate nodes, I am afraid it would not be able to realize that the tree traversal is now useless and optimize that away too. Therefore you would end up in a Θ(N) traversal of the tree and nothing done at each step...

like image 139
Matthieu M. Avatar answered Nov 17 '25 19:11

Matthieu M.


The cplusplus reference site claims it has linear complexity in the container's size as the destructor of each element must be called.

like image 37
Chris Avatar answered Nov 17 '25 20:11

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!