How to reuse a memory block previously allocated to a vector in c++

949 views Asked by At

I have multiple vectors of structure objects for different structures. Now I want to reuse the same memory for all the vector objects.i.e,Once my work is done with one vector i want to erase its elements from the memory and assign that memory to the other vector. i.e.The first vector is of one structure type object and the second vector is a structure type object of a completely different structure. I am using windows 8.1 64-bit.

2

There are 2 answers

2
273K On

When you erase vector elements, the memory allocated for the vector elements is not freed until you call std::vector::shrink_to_fit. Thus you do not have to do special actions to reuse the allocated memory.

It is not clean what you mean under

Once my work is done with one vector i want to erase its elements from the memory and assign that memory to the other vector.

You could continue using the same vector with the same memory, or you can call v1.swap(v2) to exchange allocated memories of two vectors, or you can move allocated memory of one vector to another v2 = std::move(v1).

It is applicable to vectors containing elements of a same type or pointers, that is not suitable to your case.

0
N00byEdge On

Being able to move allocated memory from a vector of one type to a vector containing another is not a feature supported by std::vector. I would suggest writing/finding another container that fits your needs.