简体   繁体   English

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

[英]Why use boost multi_array index type for indexing boost arrays in C++?

In the very first example in the boost multi_array documentation , a type for indexing is declared, viz. 在boost multi_array 文档的第一个示例中,声明了索引类型,即viz。

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

which can then be used for looping through array indices, eg 然后可以将其用于遍历数组索引,例如

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

This may be a simple question but I cannot find it explicitly documented as to why this index should be used, rather than say an unsigned int . 这可能是一个简单的问题,但是我无法找到关于为什么应使用此索引的明确记录,而不是说一个unsigned int

You cannot generically use an unsigned integer, because the base on certain dimensions could well be negative. 您一般不能使用无符号整数,因为某些尺寸的基数很可能是负数。

So if you write generic code, you would do best to do infer the index type from the array you're given. 因此,如果编写通用代码,则最好从提供的数组中推断出index类型。

Documentation says 文件说

index

  • This is a signed integral type used for indexing into A. It is also used to represent strides and index bases. 这是用于对A进行索引的带符号整数类型。它也用于表示跨步和索引基数。

A "correct" index based loop would look similar to: 基于“正确”索引的循环看起来类似于:

Live On Coliru 生活在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";
            }
        }
    }
}

Printing 印花

(-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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM