0

I would like to know how to read elements from a const boost::multi_array object. Indeed to my knowledge I can't use the operator [] because it's also used to assignement.

I have a 3-D dimentional array. So how does one get the element myArray[i][j][k] when myArray is const.

Thanks in advance.

saloua
  • 2,433
  • 4
  • 27
  • 37

2 Answers2

2

As an alternative to juanchopanza's answer you can also access elements via an index array build from a boost::array.

typedef boost::multi_array<double,3>::index tIndex;
typedef boost::array<tIndex, 3> tIndexArray;

tIndexArray index = {{ 1,2,3 }};
const double x = myArray( index );

Would give you the element myArray[1][2][3]. In case you are writing dimension-independent code this notation might be more useful than explicitly using the [] operator.

Community
  • 1
  • 1
janitor048
  • 2,045
  • 9
  • 23
  • 29
1

You can read them by value or by const reference. Assuming your array holds elements of type T:

T x = myArray[1][2][3];
const T& y = myArray[1][2][3];

If you want a pointer to an element of the multi_array, then the pointer needs to be const:

const T* y = &myArray[1][2][3];
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • In fact I am trying to add the element in an stl vector and I got a compilation error when I used the [] operator. error: initializing argument 1 of ‘void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = ]’ – saloua Mar 23 '12 at 10:28
  • @user1287983 could you add the vector declaration, the myArray declaration, and the line where you try to fill the vector? – juanchopanza Mar 23 '12 at 10:33
  • vector my_vector
    const boost::multi_array * my_array
    my_vector.push_back(& (*my_array)[i][j][k])
    – saloua Mar 23 '12 at 10:45
  • @user1287983 in this case you would need std::vector. – juanchopanza Mar 23 '12 at 10:48
  • @tuxworker I'm glad it helped. If you found the answers useful, you can up-vote them. This also applies to the answer you accepted. – juanchopanza Mar 23 '12 at 11:01