抱歉,这变成了关于数组的 3-fold 问题
我认为(动态)数组在 D 中确实很强大,但是以下问题一直困扰着我一段时间:
在 C++ 中,我可以轻松地分配具有指定值的数组,但在 DI 中还没有找到这样做的方法。当然以下没有问题:
int[] a = new int[N];
a[] = a0;
但它看起来效率低下,因为第一行将初始化为0
,而第二行将初始化为a0
。可以在 D 中完成类似于以下的操作吗?
int[] a = new int(a0)[N]; // illegal
在 std.range 中使用 stride 时我遇到的另一个效率问题:
import std.stdio;
import std.range;
struct S
{
int x;
this(this)
{
writeln("copy ", x);
}
}
void f(S[] s)
{
}
int main()
{
S[] s = new S[10];
foreach (i, ref v; s)
{
v.x = i;
}
f(stride(s, 3)); // error
return 0;
}
当然,我天真地认为我可以简单地使用 stride 创建一个新数组而不复制它的元素?在 D 中没有办法这样做,对吧?
所以我去模拟,就好像数组是步幅一样会返回,并实现f
为:
f(s, 3);
void f(S[] s, uint stride)
{
ref S get(uint i)
{
assert (i * stride < s.length);
return s[i * stride];
}
for (uint x ... )
{
get(x) = ...;
}
}
有没有办法使用索引运算符来编写 get(x) get[x]
?这样我可以静态地混合/包含跨步get
函数并保持函数的其余部分相似。我会对所采用的方法感兴趣,因为不允许本地结构访问函数范围变量(为什么不呢?)。