本文介绍了std :: vector< int> :: clear,constant time?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 std :: vector 一个原始类型,我调用 clear()(这种方式 push_back c> capacity ), clear()调用是否要在常量时间或线性时间完成?文档说它破坏了所有的元素,但如果元素是一个int,不应该有任何东西要销毁,对吗?






编辑:
我发现一个副本有一个海报,他详细解释,实现可以检查析构函数是否是微不足道的,并给出一个编译器的例子有该检查(GCC)。



If I have a std::vector with a primitive type, and I call clear() (this way push_back starts at the beginning of the capacity), is the clear() 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).

解决方案

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 to vector<T>::allocator_type::deallocate without looping over the elements and individually invoking destructors. An implementation of std::vector can use type_traits or compiler internals to determine if T 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 of std::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&lt; int&gt; :: clear,constant time?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:37