CpCd0y CpCd0y - 1 year ago 55
C++ Question

How to resize an std::vector without loosing the existing data?

I was implementing an algorithm that needs me to remove and add the same elements from a vector each iteration of a loop.


iteration 1 : |1 2 3 4| (size 4)

iteration 2 : |1 3| 2 4 (size 2 with the elements '2' and '4' still there in memory but not accounted for in the size of the vector)

iteration 3 : |1 2 3| 4 (size 3 with the element '4' still there)

Basically, I want to be able to change the value returned by the size() function without affecting the vector for performance reasons.

I know I could use another variable outside of my vector to keep track of its size, but I wanted to know if it could be possible directly inside the std::vector container.

Thanks for any help.

Answer Source

You can't do that.

The only way to reduce the value reported by size() is to resize. When resizing reduces the size, the elements outside the new size no longer exist as far as the program is concerned. Any means of accessing them (or reaccessing them, in your case) yields undefined behaviour.

If you want to track the number of elements of an array in use (say, that you are using two elements of a vector with five elements) then create an extra variable to keep track of that. To state the (hopefully) obvious, that variable will need to be kept consistent with the size of the vector (e.g. to avoid tracking that ten elements are being used in a vector with five elements).

If you want to keep the variable with the vector, make both members of a struct/class type. That class can provide member functions or operations that manage both the vector and the number of elements "in use", to ensure consistency.