一.IndexofByKey 返回索引
通过值,返回来查找键。
二·IndexOfByPredicate
通过定义二元谓词,来判定是否有符合谓词判定的元素。符合条件True的,才返回Index。这里所谓Lamda,函数就是 把函数当作参数输入,里面的参数值传递前加个[]。
这里不仅FSring 可以用谓词判断。结构体也可以,只要 == 符合被重载。这里谓词判断就是第一个属性ID 是否相同。
USTRUCT()
struct FWXFindStructInfo
{GENERATED_USTRUCT_BODY()
public:FWXFindStructInfo(){};FWXFindStructInfo(int32 inID, int32 money):ID(inID), Money(money){ID = inID;Money = money;};~FWXFindStructInfo(){};int32 ID = 0;int32 Money = 0;bool operator == (int32 inID) const{return ID == inID;}
};
void AWXArrayActor::XGFindElementByKey()
{TArray<FString> StrArr = { "Hello", "World", "of", "Tomorrow","Hello","!" };int32 Index = StrArr.IndexOfByKey(TEXT("of"));int32 IndexR = StrArr.IndexOfByPredicate([](const FString& Str) {return Str.Contains("r");});TArray<FWXFindStructInfo> StructArray;StructArray.Add(FWXFindStructInfo(1,20) );StructArray.Add(FWXFindStructInfo(2, 30));StructArray.Add(FWXFindStructInfo(4, 50));int32 IndexStructP = StructArray.IndexOfByKey(4);bool index = StructArray[2] == 2;StructArray.IndexOfByKey(4);//int32 IndexS = StructArray.IndexOfByPredicate([](const FWXFindStructInfo& Struct)// {// return ;// }//);
}
三. FindByKey,FindByPredicate 和上面类似,单不同的是他返回的是指向元素的指针。
这里auto的灵活使用,不仅可以替代指针,还可以替代指向指针的指针。
void AWXArrayActor::XGFindElementRePtr()
{TArray<FString> StrArr = { "Hello", "World", "of", "Tomorrow","Hello","!" };auto* OfPtr = StrArr.FindByKey(TEXT("of"));auto* ThePtr = StrArr.FindByKey(TEXT("the"));FString* OfPtr2 = StrArr.FindByKey(TEXT("of"));FString* ThePtr2 = StrArr.FindByKey(TEXT("the"));if (OfPtr2){(*OfPtr2) += TEXT("Modify");}TArray<AActor*> MyActors = {this,nullptr,nullptr};auto* ThisActor1 = MyActors.FindByKey(this);AActor** ThisActor2 = MyActors.FindByKey(this);// OfPtr == &StrArr[1]// ThePtr == nullptrif (AActor **ThisActor3 = MyActors.FindByKey(this)){(*ThisActor3)->SetActorLocation(FVector::ZeroVector);}auto* Len5Ptr = StrArr.FindByPredicate([](const FString& Str) {return Str.Len() == 5;});auto* Len6Ptr = StrArr.FindByPredicate([](const FString& Str) {return Str.Len() == 6;});// Len5Ptr == &StrArr[2]// Len6Ptr == nullptrauto Filter = StrArr.FilterByPredicate([](const FString& Str) {return !Str.IsEmpty() && Str[0] < TEXT('M');});
}
四.FileterByPredicate 返回符合谓词条件的数组,上面的测试案例也使用了。非常方便。