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循环一样,不会分配.

posted @   zjh6  阅读(17)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示