Daily Unreal Column #65 - Algo::Accumulate
Quick glance over how to use the Accumulate function from the Algo namespace.
Accumulate function allows us to execute a specified operation on all elements of the container and get the result in form of a single variable.
For example, we can have an array of floats. To get a sum of all floats we do the following.
TArray<float> Floats;
float Sum = Algo::Accumulate(Floats, 0.0f);
The first parameter is the container we want to get the data from, the second one is the initial value. By default, Accumulate is using TPlus<> struct that do the addition operation on all elements.
We can also pass a lambda expression that will be used to accumulate all the objects.
TArray<AMyActor*> MyActors;
Algo::Accumulate(MyActors, 0.0f, [](float TotalHealth, const AMyActor* MyActor)
{
return TotalHealth + MyActor->GetHealth();
});
Here we pass an array of actors and we accumulate the sum of their health.
Man I loved this and had no clue about it. I am already looking into Algo XD