template<typename T> class Array2D;
template<typename T>
class Line {
Array2D<T>* array;
int x;
public:
explicit Line(class Array2D<T>* array,int x) : array(array),x(x) {}
T& operator[](int y);
};
template<typename T>
class Array2D {
int w,h;
T* data;
public:
Array2D() : w(0),h(0),data(0) {}
~Array2D() { dealloc(); }
Array2D(const Array2D& other) : w(other.w),h(other.h),data(new T[w*h]) {
memcpy(data,other.data,w*h);
}
Array2D(int w,int h) {
alloc(w,h);
}
void alloc(int w,int h) {
data = new T[w*h];
this->w = w;
this->h = h;
}
void dealloc() {
delete data, data = 0;
this->w = 0;
this->h = 0;
}
T& access(int x,int y) {
return data[x + w*y];
}
T* ptr() {
return data;
}
Line<T> operator[](unsigned int x) {
return Line<T>(this,x);
}
};
template<typename T> inline T& Line<T>::operator[](int y) {
return this->array->access(x,y);
}
a demo usage:
struct v2 { int x,y; };
v2 makev2(int x,int y) { v2 v = {x,y}; return v; }
int main() {
Array2D<v2> array2d;
array2d.alloc(4,4);
for(int x=0;x<4;++x) {
for(int y=0;y<4;++y) {
array2d[x][y] = makev2(x,y);
}
}
v2* data = array2d.ptr();
for(int i=0;i<16;++i) {
std::cout<<"v2["<<i<<"] = ("<<data[i].x<<","<<data[i].y<<")\n";
}
return 0;
}
shows that objects with increasing x-position are sitting near eachother in the array...
but i still prefer
T* data = new T[width*height]; data[x + width*y] = ..
:D
anyways. i just tested and it just worked so i just shared:D


This topic is locked









