如何从数组中删除空元素或带有 nil 指针的元素?一个通用的解决方案将受到欢迎。
问问题
1765 次
1 回答
3
你可以这样写:
type
TArrayHelper = class
class function RemoveAll<T>(var Values: TArray<T>; const Value: T); static;
end;
....
function TArrayHelper.RemoveAll<T>(var Values: TArray<T>; const Value: T);
var
Index, Count: Integer;
DefaultComparer: IEqualityComparer<T>;
begin
// obtain an equality comparer for our type T
DefaultComparer := TEqualityComparer<T>.Default;
// loop over the the array, only retaining non-matching values
Count := 0;
for Index := 0 to high(Values) do begin
if not DefaultComparer.Equals(Values[Index], Value) then begin
Values[Count] := Values[Index];
inc(Count);
end;
end;
// re-size the array
SetLength(Values, Count);
end;
假设您有一个指针数组:
var
arr: TArray<Pointer>;
然后你会删除这样的nil
元素:
TArrayHelper.RemoveAll<Pointer>(arr, nil);
此代码采用简单的方法并始终使用默认比较器。对于更复杂的类型,这是不好的。例如,一些记录需要自定义比较器。您需要提供一个比较器来支持它。
上述实现尽可能简单。就性能而言,在找不到匹配值或很少找到匹配值的可能常见场景中,这很可能是一种浪费。那是因为上面的版本无条件分配,即使两个索引相同。
相反,如果存在性能问题,您可以通过逐步遍历数组直到第一个匹配项来优化代码。然后才开始移动价值。
function TArrayHelper.RemoveAll<T>(var Values: TArray<T>; const Value: T);
var
Index, Count: Integer;
DefaultComparer: IEqualityComparer<T>;
begin
// obtain an equality comparer for our type T
DefaultComparer := TEqualityComparer<T>.Default;
// step through the array until we find a match, or reach the end
Count := 0;
while (Count<=high(Values))
and not DefaultComparer.Equals(Values[Count], Value) do begin
inc(Count);
end;
// Count is either the index of the first match or one off the end
// loop over the rest of the array copying non-matching values to the next slot
for Index := Count to high(Values) do begin
if not DefaultComparer.Equals(Values[Index], Value) then begin
Values[Count] := Values[Index];
inc(Count);
end;
end;
// re-size the array
SetLength(Values, Count);
end;
如您所见,这要分析起来要困难得多。如果原始版本是瓶颈,您只会考虑这样做。
于 2014-07-04T15:15:30.513 回答