Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `std::vector<primitive>::clear()` a constant time operation?

Tags:

c++

stl

vector

Calling clear() on a vector will call the destructors of whatever is stored in the vector, which is a linear time operation. But is this the case when the vector contains primitive types like int or double?

like image 325
user2020792 Avatar asked Feb 20 '13 00:02

user2020792


People also ask

Is a vector constant time?

@shiplu.mokadd.im, inserting in a vector is constant time if the reserved size is larger than the number of elements, so it does depend on two variables. Clearing, on the other hand, doesn't depend on either the actual size or reserved size of the vector. It's a linear-time operation if you have to call destructors.

What is the time complexity of vector erase?

Erasing an element in a vector is O(n) as we have to remove the element and still need to shift all successive elements to fill the gap created. If a vector has n elements, then in the worst case we will need to shift n-1 elemets, hence the complexity is O(n).

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.

Does STD Vector clear deallocate?

Removes all elements from the vector, calling their respective destructors, leaving the container with a size of 0. The vector capacity does not change, and no reallocations happen due to calling this function.


2 Answers

I believe the answer is implementation dependent. It takes at most linear time, but some implementations may choose to optimize this.

Per 'Does clearing a vector affect its capacity?', neither MSVC nor G++ decrease the capacity of their vectors, even when .clear is called. Looking at the G++ headers, it is evident that .clear is constant-time with the default allocator, as long as the elements are scalar (primitive arithmetic types or pointers).

like image 78
nneonneo Avatar answered Oct 12 '22 18:10

nneonneo


Think about this from the POV of how a vector is likely implemented. When you invoke:

 delete [] internalPtr;

What happens?

  • The heap must reclaim a contiguous block of space
  • destructors must fire or each object in internalPtr

The former must still happen for primitive types, but destructors don't exist for them. So delete[] will execute based entirely on how fast the heap can delete a block of memory

like image 32
Doug T. Avatar answered Oct 12 '22 16:10

Doug T.