我是一名有用的助手,可以为您翻译文本。以下是您需要翻译的内容:
但是如果我要使用n维数组(扁平化),该怎么办?
例如像这样的内容:
我有一个索引问题需要解决。 我有一个已知形状的n维数组。 我想使用步幅(可能在每个维度上都不同)遍历数组。
对于固定的维度,我会使用嵌套的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维数组(扁平化),该怎么办?
例如像这样的内容:
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)
}