gpt4 book ai didi

d - 元素的就地排序

转载 作者:行者123 更新时间:2023-12-04 10:42:12 25 4
gpt4 key购买 nike

Phobos 是否有一些可变参数算法来对 l 值引用参数进行排序?就像是

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

另见 http://forum.dlang.org/thread/eweortsmcmibppmvtriw@forum.dlang.org#post-eweortsmcmibppmvtriw:40forum.dlang.org

最佳答案

Adam 的解决方案有效,尽管它使用了元素的临时副本。使用 small modification to 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 的值很大、不可分配或无法复制时才实用。

关于d - 元素的就地排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21102646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com