简体   繁体   中英

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.

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 .

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.

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 "correct" index based loop would look similar to:

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";
            }
        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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