Search code examples
c++vectormemcpy

How to manually assign vector's size?


In my application there's a part that requires me to make a copy of a container. At the moment I use std::vector (but might consider using something else). The application is very sensitive with regard to the latency. So, I was looking for a way to make a copy of a vector as fast as possible. I found that memcpy does it better than anything else. However, it does not change the internal size of the vector. I.e. vector.size() would still give me 0.

I know what slippery path I am on. I do not mind throwing away safety checks. I do know how many elements are being copied. I do not want to use vector.resize() to change the size of the destination vector (it is a slow operation).

Question:

std::vector<my_struct> destination_vector;
destination_vector.reserve(container_length);
std::memcpy(destination_vector.data(), original_vector.data(), sizeof(my_struct)*container_length);

After the code above I need to tell my destination_vector what size it is. How do I do this?

Thank you.


Solution

  • How to manually assign vector's size?

    You can't. You can only modify vector's size through the modification functions that add or remove elements such as insert, clear, resize etc.

    After the code above I need to tell my destination_vector what size it is. How do I do this?

    The mentioned code above has undefined behaviour, so it doesn't matter what you do after it.

    A simple and efficient way to copy a vector is:

    std::vector<my_struct> destination_vector(original_vector);