[C++] Cast GameState->PlayerArray

Hi,
i need to make a copy of the playerarray to sort it. but i need to cast to a my custom playerarray class. i tried the following:

	LocalArray.Empty();
	AGameStateBase* gamestate = UGameplayStatics::GetGameState(GetWorld());
	LocalArray.Append(StaticCast<TArray<TObjectPtr<ACppErstlingPlayerState>>>(gamestate->PlayerArray));
	LocalArray.Sort([](const TObjectPtr<ACppErstlingPlayerState>& A, const TObjectPtr<ACppErstlingPlayerState>& B)
		{
			return A->PlayerScore < B->PlayerScore;
		});

but it does not compile. the error is C2664. it is because of the StaticCast. How would i do it right?

Don’t. While you can use reinterpret_cast<> to cast one type to another irrespective of what it is, it is incredibly unsafe to do so - especially on an array of pointers where you can’t garauntee each entry is of the correct type.

Since you are creating a copy anyway and sorting it, it makes much more sense to just create a different array of the required type and insert the elements in order. This will be faster and safe. I haven’t tested the following, but it should work:

TArray<AMyPlayerState*> MyArray;
MyArray.Reserve(GameState->PlayerArray.Num());

for (APlayerState* Player : GameState->PlayerArray)
{
	if (AMyPlayerState* MyPS = Cast<AMyPlayerState>(Player))
	{
		const int32 Score = MyPS->Score;
		int32 InsertIndex = MyArray.Num() - 1;
		
		while (InsertIndex > 0 && MyArray[InsertIndex]->Score > Score)
		{
			InsertIndex--;
		}
		
		MyArray.Insert(MyPS, Index);
	}
}

For completions sake, here is what a reinterpret_cast would look like - but I say it again just as a disclaimer, you absolutely should not do it:

const TArray<OtherType*>& ArrayCast = reinterpret_cast<const TArray<OtherType*>&>(Array);
1 Like

Thank you. I tried the casting method :stuck_out_tongue_closed_eyes:
But something was not right, so i did the proper method.
I noticed that the line

while (InsertIndex > 0 && MyArray[InsertIndex]->Score > Score)

should be

while (InsertIndex > 0 && MyArray[InsertIndex - 1]->Score > Score)

i think.

Ah should probably have started as Num() - 1 actually, edited the post :slight_smile:

i think it would be better to subtract one like i mentioned. otherwise the second element is always inserted before the first. or am i wrong?