gpt4 book ai didi

arrays - 在 D 中切片二维数组

转载 作者:行者123 更新时间:2023-12-04 14:18:23 24 4
gpt4 key购买 nike

如果我在 D 中有一个二维数组,我知道我可以沿行创建一维切片,如下所示:

auto one_dim_arr=two_dim_arr[i][0..$]

有没有一种简单的方法可以沿列制作一维切片?做人可能认为的事情
auto one_dim_arr=two_dim_arr[0..$][j]

会做?

最佳答案

用户为此创建的类型可能如下所示:

// Demo

void main()
{
int[3][3] arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];

// simple creation
auto middleColumn = verticalSlice(arr, 1);
assert(middleColumn[1] == 5);

// iteratable
foreach (i, v; middleColumn)
assert(v == 2+i*3);

// still a slice - writing will change original array
middleColumn[1] = 17;
assert(arr[1][1] == 17);

// sliceable itself
auto center = middleColumn[1..2];
center[0] = 42;
assert(arr[1][1] == 42);

// get a normal array with .dup
int[] copyOfMiddleColumn = middleColumn.dup;
}

// Implementation

struct StepSlice(T)
{
T* ptr;
size_t length, step;

T opIndex(size_t index)
in { assert(index<length); }
body { return ptr[step*index]; }

void opIndexAssign(T value, size_t index)
in { assert(index<length); }
body { ptr[step*index] = value; }

StepSlice!T opSlice(size_t start, size_t end)
in { assert(start<=end && end<=length); }
body { return StepSlice!T(ptr+start*step, end-start, step); }

int opApply(int delegate(ref T) dg)
{
int result = 0;

for (size_t i=0; i<length; i++)
{
result = dg(ptr[i*step]);
if (result)
break;
}
return result;
}

int opApply(int delegate(ref size_t, ref T) dg)
{
int result = 0;

for (size_t i=0; i<length; i++)
{
result = dg(i, ptr[i*step]);
if (result)
break;
}
return result;
}

T[] dup()
{
T[] result = new T[length];
for (size_t i=0; i<length; i++)
result[i] = ptr[i*step];
return result;
}
}

StepSlice!T verticalSlice(T, size_t W)(T[W][] arr, size_t column)
{
return StepSlice!T(arr[0].ptr+column, arr.length, W);
}

我认为它缺少范围原语,但仍然是一个很好的起点。

std.range.stride :
import std.range;

// Demo

void main()
{
int[3][3] arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];

// simple creation
auto middleColumn = verticalSlice(arr, 1);
assert(middleColumn[1] == 5);

// iteratable
uint i;
foreach (v; middleColumn)
assert(v == 2+(i++)*3);

// still a slice - writing will change original array
middleColumn[1] = 17;
assert(arr[1][1] == 17);

// sliceable itself
auto center = middleColumn[1..2];
center[0] = 42;
assert(arr[1][1] == 42);

// get a normal array with array()
int[] copyOfMiddleColumn = array(middleColumn);
}

// Implementation

auto verticalSlice(T, size_t W)(T[W][] arr, size_t column)
{
T* start = arr[0].ptr+column;
return stride(start[0..W*arr.length], W);
}

关于arrays - 在 D 中切片二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418632/

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