FilterByPredicate 过滤数组
FilterByPredicate
在虚幻引擎中,如果你想要使用 FilterByPredicate
函数来过滤一个数组或者容器,通常是在 C++ 代码中进行操作。这个函数可以根据指定的条件(谓词)来筛选数组中的元素。以下是一个简单的示例来说明如何在虚幻引擎中使用 FilterByPredicate
函数来过滤数组。
/**
* Filters the elements in the array based on a predicate functor.
*
* @param Pred The functor to apply to each element.
* @returns TArray with the same type as this object which contains
* the subset of elements for which the functor returns true.
* @see FindByPredicate, ContainsByPredicate
*/
template <typename Predicate>
TArray<ElementType> FilterByPredicate(Predicate Pred) const
{
TArray<ElementType> FilterResults;
for (const ElementType* RESTRICT Data = GetData(), *RESTRICT DataEnd = Data + ArrayNum; Data != DataEnd; ++Data)
{
if (::Invoke(Pred, *Data))
{
FilterResults.Add(*Data);
}
}
return FilterResults;
}
假设你有一个自定义的结构体 FMyStruct
,并且你希望通过某种条件来过滤这些结构体的数组。
1. 定义结构体和谓词
首先,定义你的结构体 FMyStruct
和一个用于筛选的谓词函数:
// MyStruct.h
#pragma once
#include "CoreMinimal.h"
#include "MyStruct.generated.h"
USTRUCT(BlueprintType)
struct FMyStruct
{
GENERATED_BODY()
UPROPERTY(BlueprintReadWrite)
FString Name;
UPROPERTY(BlueprintReadWrite)
int32 Value;
};
// MyFilterPredicate.h
#pragma once
#include "CoreMinimal.h"
#include "MyStruct.h"
struct FMyFilterPredicate
{
FString NameFilter;
FMyFilterPredicate(const FString& InNameFilter)
: NameFilter(InNameFilter)
{
}
bool operator()(const FMyStruct& InItem) const
{
return InItem.Name.Contains(NameFilter);
}
};
2. 使用 FilterByPredicate
过滤数组
假设你有一个 TArray
包含了 FMyStruct
结构体的实例:
#include "MyStruct.h"
#include "MyFilterPredicate.h"
void FilterArray()
{
TArray<FMyStruct> MyArray;
// 添加一些元素到数组中
FMyStruct Element1;
Element1.Name = "Item1";
Element1.Value = 10;
MyArray.Add(Element1);
FMyStruct Element2;
Element2.Name = "Item2";
Element2.Value = 20;
MyArray.Add(Element2);
FMyStruct Element3;
Element3.Name = "AnotherItem";
Element3.Value = 30;
MyArray.Add(Element3);
// 设定要过滤的条件
FString FilterName = "Item";
// 创建一个谓词实例
FMyFilterPredicate Predicate(FilterName);
// 使用 FilterByPredicate 进行过滤
TArray<FMyStruct> FilteredArray;
MyArray.FilterByPredicate([&Predicate](const FMyStruct& InItem) {
return Predicate(InItem);
}, FilteredArray);
// 输出过滤后的结果
for (const FMyStruct& Item : FilteredArray)
{
UE_LOG(LogTemp, Warning, TEXT("Filtered Item: %s, Value: %d"), *Item.Name, Item.Value);
}
}
在上面的例子中,我们首先定义了一个 FMyFilterPredicate
结构体,用来定义我们的过滤条件(在这里是根据 Name
字段包含特定字符串)。然后,我们创建了一个数组 MyArray
并填充了一些 FMyStruct
的实例。接着,我们定义了一个过滤条件(FilterName
),并创建了一个 FMyFilterPredicate
实例。最后,我们使用 FilterByPredicate
函数来将符合条件的元素筛选到 FilteredArray
中,并打印出结果。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律