`std::vector<primitive>::clear()` 是一个常数时间操作吗? [英] Is `std::vector<primitive>::clear()` a constant time operation?
问题描述
对向量调用 clear()
将调用存储在向量中的任何内容的析构函数,这是一个线性时间操作.但是当向量包含诸如 int
或 double
之类的原始类型时,情况是否如此?
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 '清除矢量会影响其容量吗?',即使在调用 .clear
时,MSVC 和 G++ 都不会降低其向量的容量.查看 G++ 头文件,很明显 .clear
是具有默认分配器的常量时间,只要元素是标量(原始算术类型或指针).
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).
这篇关于`std::vector<primitive>::clear()` 是一个常数时间操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!