You can use a single std :: vector to contain the entire two-dimensional array and transfer it to the class to hide the details. In this example, it uses the data( row, col ) member function data( row, col ) , which returns a reference to the element in row and col . I included an example of a 2-dimensional int matrix, where each record in the array is initialized by the product of its row and col . When an instance of this class goes out of scope, the default destructor will be called and free up memory, so you don't need to forget to call delete [] to free up memory. All matrix elements will be contiguous in memory, this is caching and should give you good performance.
#include <iostream> #include <vector> #include <stdexcept> template <typename T> class matrix { std::vector<T> data_; public: size_t const rows_; size_t const cols_; matrix(size_t rows, size_t cols) : rows_(rows) , cols_(cols) , data_( rows * cols ) {} T& data( size_t row, size_t col ) { if (row > rows_ || col > cols_) throw std::out_of_range("matrix"); return data_[ row * cols_ + col ]; } }; int main( int argc, char** argv ) { matrix<int> array(100,100); for(size_t r=0; r < array.rows_; ++r) { for(size_t c=0; c < array.cols_; ++c) { array.data(r,c) = r * c; } } std::cout << "8 x 7 = " << array.data(8,7) << std::endl; return 0; // array goes out of scope here, memory released automatically }
When you run this, you will get
8 x 7 = 56
source share