【发布时间】:2015-07-15 22:04:42
【问题描述】:
我有一个要解决的索引问题。 我有一个形状已知的 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 维数组(展平)来做到这一点? 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)
}
【问题讨论】:
-
i*shape[0]+j*shape[1]+k(3D)、i*shape[0]+j*shape[1]+k*shape[2]+l(4D) 等? -
没有。这是从 i、j、k 等获取索引。我需要弄清楚如何增加一个循环,该循环以不同维度的步幅遍历多维数组。
-
也许我根据您提供的代码误解了。我假设您会为每个维度添加嵌套循环。你想要一个已经扁平化的数组上的单个循环吗?
-
阵列已经展平。只要它适用于 N 维并考虑每个暗淡的步幅,使用单个或更多循环就可以了。 N 和数组的形状是已知的,但在运行时设置。我也想避免使用递归。
-
你想要代码还是只是一个算法来生成下标?