How can I copy part of a TArray to another TArray in one line?

Say I have this TArray:

TArray Vectors;
Vectors.Init(FVector(0.f, 0.f, 0.f), 10);

Now I want a smaller array with the first 5 elements.

The way I know how to do it is by doing something like this:

TArray SubVectors;
SubVectors.Emplace(Vectors[0]);
SubVectors.Emplace(Vectors[1]);
SubVectors.Emplace(Vectors[2]);
SubVectors.Emplace(Vectors[3]);
SubVectors.Emplace(Vectors[4]);

Is there an easier way to do this by passing a range start and end in one line and copy?

I’m looking for the equivalent of C++ 11 std:vector constructor 4 from this reference:
http://en.cppreference.com/w/cpp/container/vector/vector

for (int32 i =0; i < 5, SubVectors.Emplace (Vectors [i]); ++i);

2 Likes

Another option is using one of the Append functionality. You can pass in a pointer to the array, where in your case, would be the &SubVector[Index] and the count is the number of elements you want inserted.

这是效率极低的办法,如果数字十万了,岂不是循环十万次
The efficiency is very low, if the digital thousands, not loop one hundred thousand times

This would work and is super fast (a single Memcpy for many types), but doesn’t do any checks, you’d need to check the range yourself:
image