Q: How can I define a dynamic two-dimensional array?
A: The basic idea is to use a 'vector<vector<T> >'. Use containment to write a template class that offers the desired functionality. Following skeleton code shows how to implement and use such a class:
A different approach, not using the STL 'vector' class, is shown in the following FAQ...Code:#include <vector> template <typename T> class dynamic_array { public: dynamic_array(){}; dynamic_array(int rows, int cols) { for(int i=0; i<rows; ++i) { data_.push_back(std::vector<T>(cols)); } } // other ctors .... inline std::vector<T> & operator[](int i) { return data_[i]; } inline const std::vector<T> & operator[] (int i) const { return data_[i]; } // other accessors, like at() ... void resize(int rows, int cols) { data_.resize(rows); for(int i = 0; i < rows; ++i) data_[i].resize(cols); } // other member functions, like reserve().... private: std::vector<std::vector<T> > data_; }; int main() { dynamic_array<int> a(3, 3); a[1][1] = 2; int x = a[1][1]; return 0; }
FAQ contributed by: [Gabriel Fleseriu] [Axter]


Reply With Quote
Bookmarks