gpt4 book ai didi

arrays - 如何在 Dlang 中对对象数组进行排序?

转载 作者:行者123 更新时间:2023-12-03 07:07:21 25 4
gpt4 key购买 nike

如何对 D 中的用户定义对象数组进行排序?

来自 C++ 背景,我想您必须为数组中存储的类型声明一个运算符重载,或者使用比较器函数...

如果有一个如何做到这一点的例子,我们将不胜感激。

最佳答案

你会想要std.algorithm.sort默认情况下使用 a < b,因此您的类可以覆盖 opCmp来利用这一点。

更新:只是 glampert 示例的替代方案。

import std.algorithm;
import std.stdio;

class Test {

int x;

this(int x)
{
this.x = x;
}
}

void main()
{
Test[] array = [new Test(3), new Test(1), new Test(4), new Test(2)];

writeln("Before sorting: ");
writeln(array.map!(x=>x.x));

sort!((a,b)=>a.x < b.x)(array); // Sort from least to greatest

writeln("After sorting: ");
writeln(array.map!(x=>x.x));
}

关于arrays - 如何在 Dlang 中对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185221/

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