Mail Archives: djgpp/1998/04/22/11:30:20
dmt AT bigfoot DOT com (Jeff W./DMT) writes:
> data members each of another struct type. I need a 2D array that can
> change size on the fly, i.e. maybe one minute I need a 2x2 array, and
> then 4 minutes later I need a 7x2 array, and then a 500x24 array. I
I don't know anything about vectors in STL, but
maybe this simple class will give you some ideas:
---
class vector
{
public:
vector (void)
{
width = 10;
height = 10;
data = new int[width * height];
}
~vector (void)
{
delete[] data;
}
int resize (const int _width, const int _height)
{
if ((_width <= 0) || (_height <= 0))
return -1;
width = _width;
height = _height;
delete[] data;
data = new int[width * height];
return 0;
}
int* operator[] (const int _y)
{
/* FIXME: test for index out of range. */
return &data[_y * width];
}
private:
int width;
int height;
int* data;
/* Add one more variable to keep size of data
* and reuse data (don't use delete[]/new[]) if requested
* size in 'resize' is less or equal to currently used size.
* In long run it may give a little speedup, but will waste
* more space than necessary (also helps with fragmentation?). */
};
int
main (void)
{
vector v;
int i;
v[1][2] = 3;
if (v.resize (1024, 512) != 0)
{
/* Do something. */
}
/* First index can be in [0-1023], second in [0-511]. */
v[123][456] = 789;
i = v[324][435];
return 0;
}
---
- Raw text -