# Boost.MultiArray Reference Manual

Garcia
Ronald
Indiana University
Open Systems Lab
BOOST
2002
The Trustees of Indiana University

Boost.MultiArray is composed of several components. The MultiArray concept defines a generic interface to multidimensional containers. `multi_array` is a general purpose container class that models MultiArray. `multi_array_ref` and `const_multi_array_ref` are adapter classes. Using them, you can manipulate any block of contiguous data as though it were a `multi_array`. `const_multi_array_ref` differs from `multi_array_ref` in that its elements cannot be modified through its interface. Finally, several auxiliary classes are used to create and specialize arrays and some global objects are defined as part of the library interface.

## Library Synopsis

To use Boost.MultiArray, you must include the header `boost/multi_array.hpp` in your source. This file brings the following declarations into scope:

    namespace boost {

      namespace multi_array_types {
        typedef *unspecified* index;
        typedef *unspecified* size_type;
        typedef *unspecified* difference_type;
        typedef *unspecified* index_range;
        typedef *unspecified* extent_range;
        typedef *unspecified* index_gen;
        typedef *unspecified* extent_gen;
      }

      template <typename ValueType,
                std::size_t NumDims,
                typename Allocator = std::allocator<ValueType> >
      class multi_array;

      template <typename ValueType,
                std::size_t NumDims>
      class multi_array_ref;

      template <typename ValueType,
                std::size_t NumDims>
      class const_multi_array_ref;

      multi_array_types::extent_gen extents;
      multi_array_types::index_gen  indices;

      template <typename Array, int N> class subarray_gen;
      template <typename Array, int N> class const_subarray_gen;
      template <typename Array, int N> class array_view_gen;
      template <typename Array, int N> class const_array_view_gen;

      class c_storage_order;
      class fortran_storage_order;
      template <std::size_t NumDims> class general_storage_order;

    }

&concepts;

## Array Components

Boost.MultiArray defines an array class, `multi_array`, and two adapter classes, `multi_array_ref` and `const_multi_array_ref`. The three classes model MultiArray and so they share a lot of functionality. `multi_array_ref` differs from `multi_array` in that the `multi_array` manages its own memory, while `multi_array_ref` is passed a block of memory that it expects to be externally managed. `const_multi_array_ref` differs from `multi_array_ref` in that the underlying elements it adapts cannot be modified through its interface, though some array properties, including the array shape and index bases, can be altered. Functionality the classes have in common is described below.

### Note: Preconditions, Effects, and Implementation

Throughout the following sections, small pieces of C++ code are used to specify constraints such as preconditions, effects, and postconditions. These do not necessarily describe the underlying implementation of array components; rather, they describe the expected input to and behavior of the specified operations. Failure to meet preconditions results in undefined behavior. Not all effects (i.e. copy constructors, etc.) must be mimicked exactly. The code snippets for effects intend to capture the essence of the described operation.

### Queries

    element* data();
    const element* data() const;

  This returns a pointer to the beginning of the contiguous block that contains the array's data. If all dimensions of the array are 0-indexed and stored in ascending order, this is equivalent to `origin()`. Note that `const_multi_array_ref` only provides the const version of this function.

    element* origin();
    const element* origin() const;

  This returns the origin element of the `multi_array`. Note that `const_multi_array_ref` only provides the const version of this function. (Required by MultiArray)

`const index* index_bases();`

  This returns the index bases for the `multi_array`. (Required by MultiArray)

`const index* strides();`

  This returns the strides for the `multi_array`. (Required by MultiArray)

`const size_type* shape();`

  This returns the shape of the `multi_array`. (Required by MultiArray)

### Comparators

    bool operator==(const *array-type*& rhs);
    bool operator!=(const *array-type*& rhs);
    bool operator<(const *array-type*& rhs);
    bool operator>(const *array-type*& rhs);
    bool operator>=(const *array-type*& rhs);
    bool operator<=(const *array-type*& rhs);

  Each comparator executes a lexicographical compare over the value types of the two arrays. (Required by MultiArray)

  ### Preconditions

  `element` must support the comparator corresponding to that called on `multi_array`.

  ### Complexity

  O(`num_elements()`).

### Modifiers

    template <typename SizeList>
    void reshape(const SizeList& sizes)

  This changes the shape of the `multi_array`. The number of elements and the index bases remain the same, but the number of values at each level of the nested container hierarchy may change.

  ### `SizeList` Requirements

  `SizeList` must model Collection.

  ### Preconditions

      std::accumulate(sizes.begin(),sizes.end(),size_type(1),std::times<size_type>()) == this->num_elements();
      sizes.size() == NumDims;

  ### Postconditions

  `std::equal(sizes.begin(),sizes.end(),this->shape) == true;`

    template <typename BaseList>
    void reindex(const BaseList& values);

  This changes the index bases of the `multi_array` to correspond to the the values in `values`.

  ### `BaseList` Requirements

  `BaseList` must model Collection.

  ### Preconditions

  `values.size() == NumDims;`

  ### Postconditions

  `std::equal(values.begin(),values.end(),this->index_bases());`

    void reindex(index value);

  This changes the index bases of all dimensions of the `multi_array` to `value`.

  ### Postconditions

      std::count_if(this->index_bases(),this->index_bases()+this->num_dimensions(),
                    std::bind_2nd(std::equal_to<index>(),value)) ==
                    this->num_dimensions();

&multi_array; &multi_array_ref; &const_multi_array_ref;

## Auxiliary Components

### `multi_array_types`

    namespace multi_array_types {
      typedef *unspecified* index;
      typedef *unspecified* size_type;
      typedef *unspecified* difference_type;
      typedef *unspecified* index_range;
      typedef *unspecified* extent_range;
      typedef *unspecified* index_gen;
      typedef *unspecified* extent_gen;
    }

Namespace `multi_array_types` defines types associated with `multi_array`, `multi_array_ref`, and `const_multi_array_ref` that are not dependent upon template parameters. These types find common use with all Boost.Multiarray components. They are defined in a namespace from which they can be accessed conveniently. With the exception of `extent_gen` and `extent_range`, these types fulfill the roles of the same name required by MultiArray and are described in its concept definition. `extent_gen` and `extent_range` are described below.

### `extent_range`

`extent_range` objects define half open intervals. They provide shape and index base information to `multi_array`, `multi_array_ref`, and `const_multi_array_ref` constructors. `extent_range`s are passed in aggregate to an array constructor (see `extent_gen` for more details).

#### Synopsis

    class extent_range {
    public:
      typedef multi_array_types::index      index;
      typedef multi_array_types::size_type  size_type;

      // Structors
      extent_range(index start, index finish);
      extent_range(index finish);
      ~extent_range();

      // Queries
      index start();
      index finish();
      size_type size();
    };

#### Model Of

DefaultConstructible,CopyConstructible

#### Methods and Types

`extent_range(index start, index finish)`

  This constructor defines the half open interval `[start,finish)`. The expression `finish` must be greater than `start`.

`extent_range(index finish)`

  This constructor defines the half open interval `[0,finish)`. The value of `finish` must be positive.

`index start()`

  This function returns the first index represented by the range

`index finish()`

  This function returns the upper boundary value of the half-open interval. Note that the range does not include this value.

`size_type size()`

  This function returns the size of the specified range. It is equivalent to `finish()-start()`.

### `extent_gen`

The `extent_gen` class defines an interface for aggregating array shape and indexing information to be passed to a `multi_array`, `multi_array_ref`, or `const_multi_array_ref` constructor. Its interface mimics the syntax used to declare built-in array types in C++. For example, while a 3-dimensional array of `int` values in C++ would be declared as:

    int A[3][4][5],

a similar `multi_array` would be declared:

    multi_array<int,3> A(extents[3][4][5]).

#### Synopsis

    template <std::size_t NumRanges>
    class *implementation_defined* {
    public:
      typedef multi_array_types::index index;
      typedef multi_array_types::size_type size_type;

      template <std::size_t NumRanges> class gen_type;

      gen_type<NumRanges+1>::type  operator[](const range& a_range) const;
      gen_type<NumRanges+1>::type  operator[](index idx) const;
    };

    typedef *implementation_defined*<0> extent_gen;

#### Methods and Types

`template gen_type<Ranges>::type`

  This type generator is used to specify the result of `Ranges` chained calls to `extent_gen::operator[].` The types `extent_gen` and `gen_type<0>::type` are the same.

`gen_type<NumRanges+1>::type operator[](const extent_range& a_range) const;`

  This function returns a new object containing all previous `extent_range` objects in addition to `a_range.` `extent_range` objects are aggregated by chained calls to `operator[]`.

`gen_type<NumRanges+1>::type operator[](index idx) const;`

  This function returns a new object containing all previous `extent_range` objects in addition to `extent_range(0,idx).` This function gives the array constructors a similar syntax to traditional C multidimensional array declaration.

### Global Objects

For syntactic convenience, Boost.MultiArray defines two global objects as part of its interface. These objects play the role of object generators; expressions involving them create other objects of interest.

Under some circumstances, the two global objects may be considered excessive overhead. Their construction can be prevented by defining the preprocessor symbol `BOOST_MULTI_ARRAY_NO_GENERATORS` before including `boost/multi_array.hpp.`

#### `extents`

    namespace boost {
      multi_array_base::extent_gen extents;
    }

Boost.MultiArray's array classes use the `extents` global object to specify array shape during their construction. For example, a 3 by 3 by 3 `multi_array` is constructed as follows:

    multi_array<int,3> A(extents[3][3][3]);

The same array could also be created by explicitly declaring an `extent_gen` object locally,, but the global object makes this declaration unnecessary.

#### `indices`

    namespace boost {
      multi_array_base::index_gen  indices;
    }

The MultiArray concept specifies an `index_gen` associated type that is used to create views. `indices` is a global object that serves the role of `index_gen` for all array components provided by this library and their associated subarrays and views.

For example, using the `indices` object, a view of an array `A` is constructed as follows:

    A[indices[index_range(0,5)][2][index_range(2,4)]];

### View and SubArray Generators

Boost.MultiArray provides traits classes, `subarray_gen`, `const_subarray_gen`, `array_view_gen`, and `const_array_view_gen`, for naming of array associated types within function templates. In general this is no more convenient to use than the nested type generators, but the library author found that some C++ compilers do not properly handle templates nested within function template parameter types. These generators constitute a workaround for this deficit. The following code snippet illustrates the correspondence between the `array_view_gen` traits class and the `array_view` type associated to an array:

    template <typename Array>
    void my_function() {
      typedef typename Array::template array_view<3>::type view1_t;
      typedef typename boost::array_view_gen<Array,3>::type view2_t;
      // ...
    }

In the above example, `view1_t` and `view2_t` have the same type.

### Memory Layout Specifiers

While a multidimensional array represents a hierarchy of containers of elements, at some point the elements must be laid out in memory. As a result, a single multidimensional array can be represented in memory more than one way.

For example, consider the two dimensional array shown below in matrix notation:

Here is how the above array is expressed in C++:

    int a[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

This is an example of row-major storage, where elements of each row are stored contiguously.

While C++ transparently handles accessing elements of an array, you can also manage the array and its indexing manually. One way that this may be expressed in memory is as follows:

    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
    int s[] = { 4, 1 };

With the latter declaration of `a` and strides `s`, element `a(i,j)` of the array can be accessed using the expression

    *a+i*s[0]+j*s[1]

.

The same two dimensional array could be laid out by column as follows:

    int a[] = { 0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11 };
    int s[] = { 3, 1 };

Notice that the strides here are different. As a result, The expression given above to access values will work with this pair of data and strides as well.

In addition to dimension order, it is also possible to store any dimension in descending order. For example, returning to the first example, the first dimension of the example array, the rows, could be stored in reverse, resulting in the following:

    int data[] = { 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3 };
    int *a = data + 8;
    int s[] = { -4, 1 };

Note that in this example `a` must be explicitly set to the origin. In the previous examples, the first element stored in memory was the origin; here this is no longer the case.

Alternatively, the second dimension, or the columns, could be reversed and the rows stored in ascending order:

    int data[] = { 3, 2, 1, 0,  7, 6, 5, 4, 11, 10, 9, 8 };
    int *a = data + 3;
    int s[] = { 4, -1 };

Finally, both dimensions could be stored in descending order:

    int data[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
    int *a = data + 11;
    int s[] = { -4, -1 };

``

All of the above arrays are equivalent. The expression given above for `a(i,j)` will yield the same value regardless of the memory layout.

Boost.MultiArray arrays can be created with customized storage parameters as described above. Thus, existing data can be adapted (with `multi_array_ref` or `const_multi_array_ref`) as suited to the array abstraction. A common usage of this feature would be to wrap arrays that must interoperate with Fortran routines so they can be manipulated naturally at both the C++ and Fortran levels. The following sections describe the Boost.MultiArray components used to specify memory layout.

#### `c_storage_order`

    class c_storage_order {
      c_storage_order();
    };

`c_storage_order` is used to specify that an array should store its elements using the same layout as that used by primitive C++ multidimensional arrays, that is, from last dimension to first. This is the default storage order for the arrays provided by this library.

#### `fortran_storage_order`

    class fortran_storage_order {
      fortran_storage_order();
    };

`fortran_storage_order` is used to specify that an array should store its elements using the same memory layout as a Fortran multidimensional array would, that is, from first dimension to last.

#### `general_storage_order`

    template <std::size_t NumDims>
    class general_storage_order {

      template <typename OrderingIter, typename AscendingIter>
      general_storage_order(OrderingIter ordering, AscendingIter ascending);
    };

`general_storage_order` allows the user to specify an arbitrary memory layout for the contents of an array. The constructed object is passed to the array constructor in order to specify storage order.

`OrderingIter` and `AscendingIter` must model the `InputIterator` concept. Both iterators must refer to a range of `NumDims` elements. `AscendingIter` points to objects convertible to `bool`. A value of `true` means that a dimension is stored in ascending order while `false` means that a dimension is stored in descending order. `OrderingIter` specifies the order in which dimensions are stored.

### Range Checking

By default, the array access methods `operator()` and `operator[]` perform range checking. If a supplied index is out of the range defined for an array, an assertion will abort the program. To disable range checking (for performance reasons in production releases), define the `BOOST_DISABLE_ASSERTS` preprocessor macro prior to including multi_array.hpp in an application.