c++ - 为什么在 C++ 中使用 boost multi_array 索引类型来索引 boost 数组?

标签 c++ arrays boost indexing

在 boost multi_array 的第一个示例中 documentation ,声明了一个索引类型,即。

typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;

然后可以用于循环数组索引,例如

array_type someArray(boost::extents[3][3][3]);
for(index i = 0; i < 3; i++) 
  someArray[0][0][i] = i;

这可能是一个简单的问题,但我找不到明确记录为什么应该使用这个索引,而不是说一个unsigned int

最佳答案

一般不能使用无符号整数,因为某些维度的基数很可能为负数。

因此,如果您编写通用代码,您最好从给定的数组中推断出 index 类型。

文档说

index

  • This is a signed integral type used for indexing into A. It is also used to represent strides and index bases.

“正确”的基于索引的循环看起来类似于:

Live On Coliru

#include <boost/multi_array.hpp>
#include <iostream>

int main() {
    using A = boost::multi_array<double, 3>;
    A arr(boost::extents[3][2][4]);
    std::iota(arr.data(), arr.data()+arr.num_elements(), 1.); // fill with increasing numbers

    arr.reindex(-17);

    for (A::index i = arr.index_bases()[0]; i < arr.index_bases()[0]+A::index(arr.shape()[0]); ++i) {
        for (A::index j = arr.index_bases()[1]; j < arr.index_bases()[1]+A::index(arr.shape()[1]); ++j) {
            for (A::index k = arr.index_bases()[2]; k < arr.index_bases()[2]+A::index(arr.shape()[2]); ++k) {
                std::cout << "(" << i << "," << j << "," << k << "): " << arr[i][j][k] << "\n";
            }
        }
    }
}

打印

(-17,-17,-17): 1
(-17,-17,-16): 2
(-17,-17,-15): 3
(-17,-17,-14): 4
(-17,-16,-17): 5
(-17,-16,-16): 6
(-17,-16,-15): 7
(-17,-16,-14): 8
(-16,-17,-17): 9
(-16,-17,-16): 10
(-16,-17,-15): 11
(-16,-17,-14): 12
(-16,-16,-17): 13
(-16,-16,-16): 14
(-16,-16,-15): 15
(-16,-16,-14): 16
(-15,-17,-17): 17
(-15,-17,-16): 18
(-15,-17,-15): 19
(-15,-17,-14): 20
(-15,-16,-17): 21
(-15,-16,-16): 22
(-15,-16,-15): 23
(-15,-16,-14): 24

关于c++ - 为什么在 C++ 中使用 boost multi_array 索引类型来索引 boost 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33227169/

相关文章:

c++ - cv::PCA (openCV) 是否计算数据本身的协方差矩阵?或者我们应该将协方差矩阵传递给它?

c++ - 尝试模拟纯虚拟类

arrays - Matlab : expandable array, 丢失数据

c++ - boost spirit 语义 Action

c++ - 为什么 boost::ptr_list 使用底层 void *?

c++ - C++ Builder 中的 POCO 库

javascript - 删除数组元素并将它们添加回原来的位置

c - 穿越一棵树

c++ - boost program_options中vector <string>选项的拆分值

c++ - 我怎样才能像这样显示QProgressBar?