RBS
2009-11-30 06:56:40 UTC
I am a C++ newbie. I would really appreciate some help with understanding an example I found of how to create a 2D array. I know that there are other methods out there, but this is the one I'd like to go with. My goal is to make a 2D grid where the values in the struct Props are at each grid point (I ultimately want to solve a finite difference problem). Thanks for any advice!
The example is below. What I don't understand is the following:
1) T& operator(double x, double y) { return grid_[ y*xsize_ + x ]; } What does this mean? Translation anyone? Where are the variables x and y coming from and what are they for? They don't appear anywhere else/don't seem to be declared.
2) double Row() const { return xsize_; } What does this mean?
3) Why is the Delete() function needed?
4) In the Make, Resize, and Delete functions, why are xsize_ and ysize_ defined? Why not just use row and col?
5) The code as written makes a 1-D array of xsize_ and y_size. Where (e.g., in main(), in the class definition) and how can I say how I want the grid sized? If anyone could offer and example, that would be great.
The code example is below:
template
class Grid2D
{
public:
Grid2D()
: xsize_(0), ysize_(0), grid_(0)
{ }
Grid2D(double row, double col)
: xsize_(row), ysize_(col), grid_(new T[ xsize_ * ysize_ ])
{ }
~Grid2D() { delete[ ] grid_; }
Make(double row, double col)
{
xsize_ = row;
ysize_ = col;
grid_ = new T[ xsize_ * ysize_ ]; /
}
Resize(double row, double col)
{
xsize_ = row;
ysize_ = col;
delete[ ] grid_;
grid_ = new T[ xsize_ * ysize_ ];
}
Delete()
{
xsize_ = 0;
ysize_ = 0;
delete[ ] grid_;
grid_ = 0;
}
double Row() const { return xsize_; }
double Col() const { return ysize_; }
T& operator(double x, double y) { return grid_[ y*xsize_ + x ]; } // Overload x and y
const T& operator(double x, double y) const { return grid_[ y*xsize_ + x ]; }
private:
double xsize_, ysize_;
T* grid_;
}
// T grid[10][10];
//------------------------------------
struct Props
{
double foo;
double bar; // … etc
};
//---------------------------------
int main()
{
// make a grid of Props
Grid2D