Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector capacity after copying

  • Does vector::operator= change vector capacity? If so, how?
  • Does vector's copy constructor copy capacity?

I looked through documentation but could not find a specific answer. Is it implementation dependent?

like image 807
Anycorn Avatar asked Apr 18 '10 17:04

Anycorn


People also ask

How the size of a vector increased once it is full?

Explanation: Once the vector is full i.e. number of elements in the vector becomes equal to the capacity of the vector then vector doubles its capacity i.e. if previous capacity was 2 then new capacity becomes 2 * 2 = 4 or 2 + 2 = 4.

Does vector erase change capacity?

No. That's implied by the fact that iterators, pointers and references prior to the point of erase remain valid. Reducing the capacity would require a reallocation.

Does vector clear reset size?

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

How do you increase the capacity of a vector?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.


1 Answers

All you're guaranteed is that:

  1. The vector has enough capacity to store its elements. (Obviously.)
  2. The vector won't get a new capacity until it's current capacity is full.*

So how much extra or little an implementation wants to put is up to the implementation. I think most will make capacity match size, when copying, but it cannot lower capacity. (Because of number 2 above; reallocating while there's enough room is not allowed.)

* Mostly. See Charles' comments below.

like image 65
GManNickG Avatar answered Oct 03 '22 22:10

GManNickG