Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 678
Mr. Smith Avatar asked Dec 30 '12 20:12

Mr. Smith


People also ask

How do you remove duplicates from a vector vector?

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.

What does vector Clear () do?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

How do you clear a std::vector?

The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.


2 Answers

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).

like image 67
Charles Salvia Avatar answered Oct 26 '22 15:10

Charles Salvia


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.

like image 45
Lightness Races in Orbit Avatar answered Oct 26 '22 14:10

Lightness Races in Orbit