1

私は D を学習中です (C++ よりも初心者にやさしい言語であると判断しました)。D で一般的なクイックソートを実装する練習を自分に課すことにしました。コンパイルして、文字列をソートするときに奇妙なエラーをスローします。

これが私のコードです:

import std.stdio, std.algorithm;



T[] quickSort(T)(T[] input) {
   if (input.length <= 1) {return input;}
   ulong i = input.length/2;
   auto pivot = input[i];
   input = input.remove(i);
   T[] lesser = [];
   T[] greater = [];
   foreach (x; input) {
      if (x<=pivot)
      {
         lesser ~= x;
      }
      else 
      {
         greater ~=x;
      }
   }
   return (quickSort(lesser) ~ cast(T)pivot ~ quickSort(greater));
}
void main() {
   //Sort integers, this works fine
   //writeln(quickSort([1,4,3,2,5]));
   //Sort string, throws weird error
   writeln(quickSort("oidfaosnuidafpsbufiadsb"));
}

文字列で実行すると、次のエラーがスローされます。

/usr/share/dmd/src/phobos/std/algorithm.d(7397): Error: template std.algorithm.move does not match any function template declaration. Candidates are:
/usr/share/dmd/src/phobos/std/algorithm.d(1537):        std.algorithm.move(T)(ref T source, ref T target)
/usr/share/dmd/src/phobos/std/algorithm.d(1630):        std.algorithm.move(T)(ref T source)
/usr/share/dmd/src/phobos/std/algorithm.d(1537): Error: template std.algorithm.move cannot deduce template function from argument types !()(dchar, dchar)
/usr/share/dmd/src/phobos/std/algorithm.d(7405): Error: template std.algorithm.moveAll does not match any function template declaration. Candidates are:
/usr/share/dmd/src/phobos/std/algorithm.d(1786):        std.algorithm.moveAll(Range1, Range2)(Range1 src, Range2 tgt) if (isInputRange!(Range1) && isInputRange!(Range2) && is(typeof(move(src.front, tgt.front))))
/usr/share/dmd/src/phobos/std/algorithm.d(7405): Error: template std.algorithm.moveAll(Range1, Range2)(Range1 src, Range2 tgt) if (isInputRange!(Range1) && isInputRange!(Range2) && is(typeof(move(src.front, tgt.front)))) cannot deduce template function from argument types !()(string, string)
helloworld.d(9): Error: template instance std.algorithm.remove!(cast(SwapStrategy)2, string, ulong) error instantiating
helloworld.d(31):        instantiated from here: quickSort!(immutable(char))
helloworld.d(31): Error: template instance helloworld.quickSort!(immutable(char)) error instantiating
4

2 に答える 2

3

問題は、文字列が不変であるためremove機能しないことです(文字列を操作するため)

連結でピボットを削除したり挿入したりしないことで、これを修正できます。

auto pivot = input[i];
//input = input.remove(i); //<- remove this line
T[] lesser = [];
//...
return (quickSort(lesser) ~ quickSort(greater)); //<- remove cast(T)pivot ~ 

またはdupを渡すことによって:

writeln(quickSort("oidfaosnuidafpsbufiadsb".dup));
于 2013-09-27T00:03:27.577 に答える
3

文字列を utf-32 にするには、文字列の後ろに「d」を付ける必要があります。そうしないと、remove はそれを受け入れません。

writeln(quickSort("oidfaosnuidafpsbufiadsb"d.dup));
于 2013-09-27T01:54:11.380 に答える