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
?
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).
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
In this link:
http://www.cplusplus.com/reference/vector/vector/clear/
It says complexity of clear()
is linear in size (destructions).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.