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?
A vector element is removed with the vector erase member function. The syntax is: constexpr iterator erase(const_iterator position); The argument is an iterator that points to the element, to be removed.
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
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).
The standard makes no guarantees about the complexity of std::vector::clear
, though you'd expect the operation to be linear in the container's size for complex element types, and constant for PODs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With