#ifndef __FIELD_2D_H__ #define __FIELD_2D_H__ #include #include template class Field2D { T *data; size_t *count; size_t nx, ny; public: typedef T ElementType; Field2D() : data(nullptr), count(nullptr), nx(0), ny(0) { } Field2D( size_t nx, size_t ny) : nx(nx), ny(ny) { data = new T[nx * ny]; count = new size_t; *count = 1; } Field2D( const Field2D& field ) { data = field.data; count = field.count; nx = field.nx; ny = field.ny; if (count) ++*count; } ~Field2D() { if (count && --*count == 0) { delete[] data; delete count; } } const Field2D& operator=(const Field2D& that) { assert( nx == that.nx && ny == that.ny ); for(size_t i = 0; i < nx; ++i) for(size_t j = 0; j < ny; ++j) data[i*nx+j] = that.data[i*nx+j]; return *this; } size_t width() const { return nx; } size_t height() const { return ny; } size_t area() const { return nx * ny; } T& operator()(size_t ix, size_t iy) { assert( ix < nx && iy < ny ); return data[ix*ny + iy]; } T operator()(size_t ix, size_t iy) const { assert( ix < nx && iy < ny ); return data[ix*ny + iy]; } void fill(T val) { for(size_t i = 0; i < nx; ++i) for(size_t j = 0; j < ny; ++j) data[i*ny+j] = val; } }; #endif