简体   繁体   中英

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

I have multiple vectors of structure objects for different structures. Now I want to reuse the same memory for all the vector objects.ie,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. ieThe 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM