Phobos には、左辺値参照引数を配置する可変アルゴリズムがありますか? 何かのようなもの
int a=3;
int b=2;
int c=1;
orderInPlace(a,b,c);
// a is now 1
// b is now 2
// c is now 3
order(a, b, c)
また、タプルを返す機能的なバリアント、たとえばもいいでしょう。
そうでない場合は、 を使用する必要があると思いますstd.algorithm:swap
。
Phobos には、左辺値参照引数を配置する可変アルゴリズムがありますか? 何かのようなもの
int a=3;
int b=2;
int c=1;
orderInPlace(a,b,c);
// a is now 1
// b is now 2
// c is now 3
order(a, b, c)
また、タプルを返す機能的なバリアント、たとえばもいいでしょう。
そうでない場合は、 を使用する必要があると思いますstd.algorithm:swap
。
Adam のソリューションは機能しますが、要素の一時的なコピーを使用します。std.algorithmを少し変更すると、要素をその場でソートするバージョンを作成できます。
import std.algorithm;
import std.stdio;
import std.traits;
import std.typecons;
struct SortableRef(T)
{
private T * _p;
@property ref T value() { return *_p; }
alias value this;
void opAssign(T * value) { _p = value; }
@disable void opAssign(SortableRef!T value);
void proxySwap(SortableRef!T other) { swap(*_p, *other._p); }
}
template PointerTo(T) { alias T* PointerTo; }
void orderInPlace(T...)(ref T values)
if (!is(CommonType!(staticMap!(PointerTo, T)) == void))
{
alias CommonType!T E;
SortableRef!E[values.length] references;
foreach (i, ref v; values)
references[i] = &v;
references[].sort();
}
void main()
{
int a=3;
int b=1;
int c=2;
orderInPlace(a, b, c);
writeln([a, b, c]);
}
ただし、渡された値orderInPlace
が大きいか、割り当てられないか、コピーするのが実際的でない場合にのみ実用的です。