c++11 - Nice way to create a dynamic 2D matrix in C++ 11 -


i know how create dynamic 2d matrix using new , free using delete. since c++ 11 here many new memory features such unique_ptr, array container etc.; nice way create 2d matrix 1 needs not free matrix explicitly using delete operator?

one of simplest ways use vector of vectors

const int n = 10; const int m = 10; vector<vector<int>> matrix2d(n, vector<int>(m, 0)); // 10x10 zero-initialized matrix matrix2d[0][0] = 42; 

you of course use single vector , wrap accessor class

vector<int> matrix(n * m, 0) // ditto above, needs stride-aware accessors 

i'll post small example here completeness' sake

template <typename t> class matrix2d {     std::vector<t> data;     unsigned int sizex, sizey; public:     matrix2d (unsigned int x, unsigned int y)         : sizex (x), sizey (y) {         data.resize (sizex*sizey);     }      t& operator()(unsigned int x, unsigned int y) {         if (x >= sizex || y>= sizey)             throw std::out_of_range("oob access"); // throw more appropriate         return data[sizex*y + x]; // stride-aware access     } }; 

live example

or perhaps combine way smart pointer. notice vector<vector<int>> approach should used caution since vectors independent each other , there's nothing enforce should keep size fixed.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -