std :: vector< int> :: clear,constant time? [英] std::vector<int>::clear, constant time?
问题描述
如果我有一个 std :: vector
一个原始类型,我调用 clear()
(这种方式 push_back
c> capacity ), clear()
调用是否要在常量时间或线性时间完成?文档说它破坏了所有的元素,但如果元素是一个int,不应该有任何东西要销毁,对吗?
编辑:
我发现一个副本有一个海报,他详细解释,实现可以检查析构函数是否是微不足道的,并给出一个编译器的例子有该检查(GCC)。
解决方案这取决于如何实现向量,但是一个对象的数组与简单的析构函数(包括PODs像内置的整数类型例如
int
)应该能够通过对向量< T> :: allocator_type :: deallocate $ c $的单个调用来安全地解除分配c>没有循环元素和单独调用析构函数。
std :: vector
的实现可以使用type_traits
或编译器内部来确定T
有一个简单的析构函数,并相应地释放内部数组。你需要检查你的实现的源代码来了解它的功能,但是大多数主流实现std :: vector
会给你的类型具有简单的析构函数(或至少对于整数类型和其他POD的恒定时间)。Possible Duplicate:
What is the complexity of std::vector<T>::clear() when T is a primitive type?If I have a
std::vector
with a primitive type, and I callclear()
(this waypush_back
starts at the beginning of thecapacity
), is theclear()
call going to be completed in constant time or linear time? The documentation says it destroys all the elements, but if the element is an int, there shouldn't be anything to destroy, right?
edit: I found a duplicate that has a poster who explains in detail that the implementation can check whether the destructor is trivial, and gives an example of one compiler that has that check (GCC).
What is the complexity of std::vector<T>::clear() when T is a primitive type?
解决方案It depends on how the vector is implemented, but an array of objects with trivial destructors (which includes PODs like built-in integral types such as
int
) should be able to be deallocated safely with a single call tovector<T>::allocator_type::deallocate
without looping over the elements and individually invoking destructors. An implementation ofstd::vector
can usetype_traits
or compiler internals to determine ifT
has a trivial destructor, and deallocate the internal array accordingly. You'll need to check the source code of your implementation to find out what it does, but most mainstream implementations ofstd::vector
will give you constant-time deallocation for types with trivial destructors (or at least constant time for integral types and other PODs).这篇关于std :: vector< int> :: clear,constant time?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!