Here is a summary of how to build a 2d array in C++ using various techniques.
Static 2D Matrix:
const size_t N = 25; // the dimension of the matrix
int matrix[N][N]; // N must be known at compile-time.
// you can't change the size of N afterwards
for(size_t i = 0; i < N; ++i)
{
for(size_t j = 0; j < N; ++j)
{
matrix[i][j] = /* random value! */;
}
}
Dynamic 2d Matrix:
const size_t N = 25; // the dimension of the matrix
int** matrix = new int*[N]; // each element is a pointer to an array.
for(size_t i = 0; i < N; ++i)
matrix[i] = new int[N]; // build rows
for(size_t i = 0; i < N; ++i)
{
for(size_t j = 0; j < N; ++j)
{
matrix[i][j] = /* random value! */;
}
}
// DON'T FORGET TO DELETE THE MATRIX!
for(size_t i = 0; i < N; ++i)
delete matrix[i];
delete matrix;
Matrix using std::vector:
// Note: This has some additional overhead
// This overhead would be eliminated once C++0x becomes main-stream ;)
// I am talking about r-value references specifically.
typedef vector< vector<int> > Matrix;
typedef vector<int> Row;
const size_t N = 25; // the dimension of the matrix
Matrix matrix(N);
for(size_t i = 0; i < N; ++i)
{
Row row(N);
for(size_t j = 0; j < N; ++j)
{
row[j] = /* random value! */;
}
matrix.push_back(row); // push each row after you fill it
}
// Once you fill the matrix, you can use it like native arrays
for(size_t i = 0; i < N; ++i)
{
for(size_t j = 0; j < N; ++j)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
// Note that this is much more efficient than using std::vector!
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 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;
}