Can I recast the memory in a std::vector to a completely different type?

Viewed 115

I have a struct like this:

struct Vector3
{
    float data[3];
}

I have another 3rd party library which reads the contents of a file, and loads the data into a vector<float>, which is passed to it by reference:

void ThirdPartyReadData(std::string fileName, std::vector<float> &vecFloat);

I need to give that data to another 3rd party function, which wants the data in the form of vector<Vector3>:

void ThirdPartyUseData(std::vector<Vector3> &vecVector3);

The obvious solution to this is to simply copy all of the data out of the vector<float> into the vector<Vector3>, but it seems like a waste. That memory is already in exactly the format is would be in when copied to the vector<Vector3>. I wonder if there is some way to re-construct the original vector<float> as a vector<Vector3>, without freeing all of that memory?

1 Answers

No. There is no way to avoid copying when converting from std::vector<float> to std::vector<Vector3>.

At least one of the third party libraries would have to be changed in order to avoid copying. Either read the file directly onto std::vector<Vector3> by changing the reader, or change the user to accept a std::vector<float>. Or even better, use iterators or ranges to make the library more generally useful.

Related