Convert std::vector to TArray

Hey all,

So I’m stumped. I am working with a third-party library that outputs a std::vector. This vector is to be converted into a TArray for use in the CreateMeshSection_LinearColor element of the procedural mesh generation system. I have yet to find an effective method to convert this data, because converting from vectors to TArrays is not terribly clean, and the transition from float to fvector is not common. This may be an impossible task (at which point I may have to edit the third party library), however I thought I would ask to see if this was possible. Thanks!

Cheers,
Gazebo

Well you wont find a premade method for that, but it can be very simply don manually like this for example:

std::vector<float> vec;
TArray<float> arr;
arr.SetNumUninitialized(vec.size());

for(int i=0; i< vec.size(); i++){
  arr[i] = vec[i];
}

You can of course also convert any types in that loop if you need to.

The other answer doing it using a loop is absolutely correct, but there is also a more compact solution using the raw version of Tarray::Append (API doc)

Note that this does only work for std::vector and C arrays, because the memory used internally has to be in continuous order, which is only guaranteed by std::vector. Don’t use it with std::list, std::deque or any other std container.

std::vector<float> vec = {0.f, 1.5f, 4.f};
TArray<float> arr;
arr.Append(&vec[0], vec.size());

Or using an C array

float arr[] = {0.f, 1.5f, 4.f};
TArray<float> arr;
arr.Append(arr, 3);
1 Like