Search code examples
c++boostboost-multi-array

Accessing dimension of boost multi-arrays in C++


When I run the following with warning flags I get a type conversion warning.

#include <boost/multi_array.hpp>

void function (boost::multi_array<unsigned char, 2> matrix) {
  int nrows = matrix.shape()[0];
  int ncols = matrix.shape()[1];
}

See warning message below. Does this mean I am implicitly converting a 'long unsigned int' into a regular 'int'?

If so, I think this is what I want (need to perform calculations with nrows, ncols afterwards), and so how would I make the conversion explicit?

image.cpp:93:32: warning: conversion to ‘int’ from ‘boost::const_multi_array_ref<float, 2ul, float*>::size_type {aka long unsigned int}’ may alter its value [-Wconversion]
     int nrows = matrix.shape()[0];

Solution

  • Does this mean I am implicitly converting a 'long unsigned int' into a regular 'int'?

    Yes, that is what it means.

    If you don't want the warning then don't make nrows and ncols be of type int. The easiest thing to do is to just let the compiler deduce the type i.e.

    auto nrows = matrix.shape()[0];
    auto ncols = matrix.shape()[1];
    

    or you can make them of type size_t, which is what the standard library uses for the size of containers and won't emit a warning.