Click to See Complete Forum and Search --> : STL General: How to declare and use two-dimensional arrays?


Yves M
February 13th, 2003, 01:09 PM
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:


#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&lt;std::vector&lt;T&gt; &gt; data_;
};


int main()
{
dynamic_array&lt;int&gt; a(3, 3);
a[1][1] = 2;
int x = a[1][1];
return 0;
}

A different approach, not using the STL 'vector' class, is shown in the following FAQ (http://www.codeguru.com/forum/showthread.php?s=&threadid=297838)...


FAQ contributed by: [Gabriel Fleseriu (http://www.codeguru.com/forum/member.php?u=54586)] [Axter (http://www.codeguru.com/forum/member.php?u=35679)]
<br><br>