gpt4 book ai didi

c++ - 如何用stride遍历一个n维数组

转载 作者:太空狗 更新时间:2023-10-29 23:15:16 24 4
gpt4 key购买 nike

我有一个要解决的索引问题。我有一个已知形状的 n 维数组。我想大步遍历数组(每个 dim 可能不同)。

对于固定尺寸,我会使用嵌套的 for 循环(小数组)并按步长递增:

std::vector<int> shape = {10, 10}; // h,w
int num_dim = shape.size();
std::vector<int> stride = {1,2};

for (int i = 0; i< shape[0]; i+=stride[0]) {
for (int j = 0; j< shape[1]; j+=stride[1]) {
//print flattened index (row major)
printf("index: %d\n",i*shape[0]+j);
}

}

但是我该如何处理一个 n 维数组(展平)呢?IE。像这样的东西:

std::vector<int> shape = {10, 10}; // h,w
int num_dim = shape.size();
std::vector<int> stride = {1,2};

int shape_size = 1;
for (int i = 0; i< num_dim; ++i) {
shape_size *= shape[i];
}

int ind = 0;
while (ind < shape_size) {
// somehow incr ind by the correct amount according to stride, and shape
// or check if the ind is in the stride (less desirable)
}

最佳答案

class Foo {
public:
std::vector<int> shape = { 10, 10 }; // h,w
std::vector<int> stride = { 1, 2 };
std::vector<int> d = { 0, 0 };
bool add_end = false;
void AddStride(int index) {
d[index] += stride[index];
if (d[index] < shape[index]) {
return;
} else {
if (index == 0) {
add_end = true;
return;
}
d[index] = 0;
index--;
AddStride(index);
}
}
bool AddStride() {
AddStride(d.size() - 1);
}
};
int main() {
Foo f;
while(f.add_end != true) {
//do something
f.AddStride();
}
}

关于c++ - 如何用stride遍历一个n维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065387/

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