Is `std::vector<primitive>::clear()` a constant time operation?

喜夏-厌秋 提交于 2019-12-10 12:36:00

问题


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?


回答1:


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




回答2:


Think about this from the POV of how a vector is likely implemented. When you invoke:

 delete [] internalPtr;

What happens?

  • The heap must reclaim a contiguous block of space
  • destructors must fire or each object in internalPtr

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




回答3:


In this link:

http://www.cplusplus.com/reference/vector/vector/clear/

It says complexity of clear() is linear in size (destructions).




回答4:


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



来源:https://stackoverflow.com/questions/14970349/is-stdvectorprimitiveclear-a-constant-time-operation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!