Multidimensional Arrays in C++

Declaring and initializing multi-dimensional arrays in C++ can be done not just by way of traditional pointer arithmetic, but using the STL / Boost libraries as well.  Here are some examples:

2D arrays using std::vector

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int x = 5;
    int y = 5;
    int count = 0;

    vector<vector<int>> Set( x, vector<int>( y ) );

    for ( int i = 0; i < x; i++ ) {
          for ( int j = 0; j < y; j++ ) {
                Set[ i ][ j ] = count++;
          }
    }                

    for ( int i = 0; i < x; i++ )
    {
          copy( Set[ i ].begin(),
                  Set[ i ].end(),
                  ostream_iterator<int>( cout, " " ) );
          cout << endl;
    }    

    return 0;
}

3D Arrays using Boost

Lifted directly from the Boost User Documentation:

#include "boost/multi_array.hpp"
#include <cassert>

int main()
{
  // Create a 3D array that is 3 x 4 x 2
  typedef boost::multi_array<double, 3> array_type;
  typedef array_type::index index;
  array_type A( boost::extents[ 3 ][ 4 ][ 2 ] );

  // Assign values to the array elements
  int values = 0;
  for(index i = 0; i != 3; ++i)
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        A[i][j][k] = values++;

  // Verify values
  int verify = 0;
  for(index i = 0; i != 3; ++i)
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        assert(A[i][j][k] == verify++);

  return 0;
}

Leave a Reply