gpt4 book ai didi

arrays - D 动态数组初始化、stride和索引操作

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

抱歉,这变成了关于数组的 3 重问题

我认为(动态)数组在 D 中确实很强大,但以下问题困扰了我一段时间:

在 C++ 中,我可以轻松地分配具有指定值的数组,但在 D 中我还没有找到这样做的方法。肯定没有以下问题:

int[] a = new int[N];
a[] = a0;

但它看起来效率低下,因为第一行将用 0 初始化, 和 2 一样 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 中没有办法这样做,对吗?

所以我去模拟,就好像数组是 stride 会返回一样,并实现了 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功能并保持其余功能相似。我对所采用的方法很感兴趣,因为不允许本地结构访问函数作用域变量(为什么不呢?)。

最佳答案

But it looks inefficient, since line one will initialize with 0, and like 2 with a0. Could something similar to the following be done in D?



使用 std.array.uninitializedArray
S[] s = uninitializedArray!(S[])(N);
s[] = a0;

Surely I was naive thinking I could simply use stride to create a new array without copying it's elements? There is no way to do so in D, right?



您的职能 f有一个 S[]作为一个论点,这与 stride 不同返回。解决这个问题的 D 方法是让您的 f函数通过使其成为模板来接受任何范围:
void f(Range)(Range s)
{
foreach (item; s)
// use item
}

S[] s = new S[10];
f(s); // works
f(stride(s, 3)); // works too

或者,您可以复制数组:
f(array(stride(s, 3)));

但是如果它很大,您可能希望避免复制整个数组。

Would there be a way to instead write get(x) using the index operator get[x]? This way I could statically mixin / include the striding get function and keep the rest of the function similar. I'd be interested in the approach taken, since a local struct is not allowed to access function scope variables (why not?).



您可以在自己的结构中重载索引运算符。
struct StrideArray
{
this(S[] s, uint stride) { m_array = s; m_stride = stride; }

S opIndex(size_t i) { return s[i * m_stride]; }
void opIndexAssign(size_t i, S value) { s[i * m_stride] = value; }

private S[] m_array;
private uint m_stride;
}

这是(某种)实际的方式 stride功能有效。我建议阅读 Ranges .

关于arrays - D 动态数组初始化、stride和索引操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8363728/

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