-
February 13th, 2003, 01:09 PM
#1
STL General: How to declare and use two-dimensional arrays ?
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:
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;
}
A different approach, not using the STL 'vector' class, is shown in the following FAQ...
FAQ contributed by: [Gabriel Fleseriu] [Axter]
Last edited by Andreas Masur; July 24th, 2005 at 12:55 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|