std :: vector< int> :: clear,constant time? [英] std::vector<int>::clear, constant time?

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

问题描述


可能重复:


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






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






解决方案

这取决于如何实现向量,但是一个对象的数组与简单的析构函数(包括PODs像内置的整数类型例如 int )应该能够通过对向量< T> :: allocator_type :: deallocate 没有循环元素和单独调用析构函数。 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 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).

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 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆