Unfortunately as of C++14 there’s no dynamic size matrix class in the C++ standard library. Matrix classes that support dynamic size are however available from a number of 3rd party libraries, including the Boost Matrix library (a sub-library within the Boost library).
If you don’t want a dependency on Boost or some other library, then one poor man’s dynamic size matrix in C++ is just like
vector<vector<int>> m( 3, vector<int>( 7 ) );
… where vector
is std::vector
. The matrix is here created by copying a row vector n times where n is the number of rows, here 3. It has the advantage of providing the same m[y]
indexing notation as for a fixed size raw array matrix, but it’s a bit inefficient because it involves a dynamic allocation for each row, and it’s a bit unsafe because it’s possible to inadvertently resize a row.
A more safe and efficient approach is to use a single vector as storage for the matrix, and map the client code’s (x, y) to a corresponding index in that vector:
https://codeeval.dev/gist/b2fb3b1114236cfa647c4faa135a9812
The above code is not industrial grade: it’s designed to show the basic principles, and serve the needs of students learning C++.
For example, one may define operator()
overloads to simplify the indexing notation.