Reputation: 239
Calling clear()
on a vector will call the destructors of whatever is stored in the vector, which is a linear time operation. But is this the case when the vector contains primitive types like int
or double
?
Upvotes: 11
Views: 888
Reputation: 2606
Well.. it says that clear() is linear, but we also know that it calls the destructor of every item...
http://www.cplusplus.com/reference/vector/vector/clear/
What if the destructor call ist not linear?
However, on primitives the destructor-call is linear (or constant, this is not important unless it is not more than linear)
so yes, on primitives is clear() always a linear operation
Upvotes: 0
Reputation: 179422
I believe the answer is implementation dependent. It takes at most linear time, but some implementations may choose to optimize this.
Per 'Does clearing a vector affect its capacity?', neither MSVC nor G++ decrease the capacity of their vectors, even when .clear
is called. Looking at the G++ headers, it is evident that .clear
is constant-time with the default allocator, as long as the elements are scalar (primitive arithmetic types or pointers).
Upvotes: 5
Reputation: 2373
In this link:
http://www.cplusplus.com/reference/vector/vector/clear/
It says complexity of clear()
is linear in size (destructions).
Upvotes: 0
Reputation: 65619
Think about this from the POV of how a vector
is likely implemented. When you invoke:
delete [] internalPtr;
What happens?
The former must still happen for primitive types, but destructors don't exist for them. So delete[]
will execute based entirely on how fast the heap can delete a block of memory
Upvotes: 2