d去掉元素
去掉元素
auto dropSlice(T)(T[] array, T which)
{
T[] result;
size_t i; // old index
foreach(index, element; array)
{
if(element == which) {
result ~= array[i..index]; // slice off
i = index + 1;
}
}
return result ~ array[i..$]; // last slice
}
void main()
{
char[] dizi = "abcdefdg".dup;
dizi.dropSlice('d').writeln;
可以这样:
auto drop(T)(ref T[] arr, T which)
{
import std.algorithm, std.range;
auto f = arr.find(which);
debug if(f.empty) throw ...;
auto result = arr.front;
arr = arr.remove(&f[0] - &arr[0]);//很讨厌
return result;
}
可以这样:
auto drop(T)(ref T[] arr, T which)
{
import std.algorithm, std.range, std.exception;
auto i = arr.countUntil(which);
//countUntil
debug enforce(i < arr.length, "未发现");
auto result = arr[i];
arr = arr.remove(i);
return result;
}
或者用枚举:
auto f = arr.enumerate.find!((v, w) => v[1] == w)(which);
auto result = f.front[1];
arr = arr.remove(result[0]);
return result;
首先,你忽略了循环.其次,返回值是数组的第一个元素.它应该如下:
auto drop2(T)(ref T[] arr, T which)
{
//auto f = arr.find(which);
auto f = arr.find!(a => a == which);
//debug if(f.empty) throw ...;
auto result = f.front; // arr.front;
//arr = arr.remove(&f[0] - &arr[0]);
arr = remove!(a => a == which)(arr);
return result;
}
一行就够了:
return remove!(a => a == which)(arr);
是的,应该这样:
auto result = f.front;
但
arr = remove!(a => a == which)(arr);
这将再次遍历数组,而不是仅删除已知道的一个索引.而且,即使有多个匹配项,原始代码也只删除了一个元素.你的全部删除了.
返回的是被删除元素.
代码,未用函数式编程.
这两个不一样:
arr.find(val); //是for循环,比较每个元素
arr.find!(v => v == val);//更贵
//要求环境指针,可能会分配.
意思是说,如果arr.find!(someLambda)这样,如果λ要用外部数据,可能就要垃集.
而,arr.find(value)与for循环一样,不会分配.
浙公网安备 33010602011771号