M-Askman
M-Askman

Reputation: 400

will vector reallocate when push_back after shrink capacity to zero?

  1. before push back, i shrink capacity to zero, then i push back item into vector, will it reallocate?
  2. is reallocate means slow down in performance?
  3. if so, why need to shrink capacity to zero or fit the size?

    vector<int> mandy2(5);
    vector<int>().swap(mandy2);
    
    printf("mandy2 size: %d\n", mandy2.size());
    printf("mandy2 capacity: %d\n", mandy2.capacity());
    
    mandy2.push_back(1);
    mandy2.push_back(2);
    mandy2.push_back(6);
    

Upvotes: 0

Views: 379

Answers (3)

Alok Save
Alok Save

Reputation: 206536

before push back, i shrink capacity to zero, then i push back item into vector, will it reallocate?

Yes it will.

Reference the doccumentation:

void push_back ( const T& x );

Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x.

This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call. Reallocations invalidate all previously obtained iterators, references and pointers.


Is reallocate means slow down in performance?

Theorotically,Yes!
How much it hurts you can only be conclusively said after profiling your code for the same.


If so, why need to shrink capacity to zero or fit the size?

You do that only, if you know that you do not want to add any further elements to the vector, that ensures your vector does not consume more memory than you would actually need ever.

Upvotes: 1

Mankarse
Mankarse

Reputation: 40603

  1. Yes.
  2. Yes, probably. It also means that iterators, pointers and references to elements in the container are invalidated.
  3. Shrinking the capacity will reduce the memory usage of the container. This will free up memory for other parts of the program to use.

Upvotes: 2

NPE
NPE

Reputation: 500357

std::vector will reallocate whenever the capacity is insufficient to accommodate the push_back request.

before push back, i shrink capacity to zero, then i push back item into vector, will it reallocate?

Yes.

is reallocate means slow down in performance?

In the long run, no (since each insertion takes O(1) amortized time). I wouldn't worry about it unless profiling shows it is a problem.

if so, why need to shrink capacity to zero or fit the size?

I don't understand this question.

Upvotes: 2

Related Questions