Skip to content

Instantly share code, notes, and snippets.

Created April 25, 2015 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/04849e1cb96ed2c5169b to your computer and use it in GitHub Desktop.
Save anonymous/04849e1cb96ed2c5169b to your computer and use it in GitHub Desktop.
#ifndef ARRAY_2D_H
#define ARRAY_2D_H
#include <memory>
template <class T>
class Array2D
{
unsigned int width_;
unsigned int height_;
unsigned int size_;
std::unique_ptr<T> data_;
public:
class iterator
{
friend Array2D;
T* ptr;
iterator(T* p) : ptr(p) {}
public:
iterator() : ptr(NULL) {}
iterator& operator --()
{
ptr--;
return *this;
}
iterator& operator ++()
{
ptr++;
return *this;
}
iterator& operator -=(int x)
{
ptr -= x;
return *this;
}
iterator& operator +=(int x)
{
ptr += x;
return *this;
}
bool operator !=(iterator& i)
{
return ptr != i.ptr;
}
T* operator ->()
{
return ptr;
}
T* operator *()
{
return ptr;
}
};
Array2D(){ data_ = NULL; }
Array2D(unsigned wset, unsigned hset)
: width_(wset), height_(hset), size_(width * height_)
{
data_ = std::unique_ptr<T>(new T[size_]);
}
~Array2D()
{
}
Array2D(Array2D const& a)
{
width_ = a.width_;
height_ = a.height_;
size_ = a.size_;
data_ = std::unique_ptr<T>(new T[size_]);
memcpy(data_.get(), a.data_.get(), size_ * sizeof(T));
}
Array2D& operator= (Array2D const& a)
{
width_ = a.width_;
height_ = a.height_;
size_ = a.width_ * a.height_;
data_ = std::unique_ptr<T>(new T[size_]);
memcpy(data_.get(), a.data_.get(), size_ * sizeof(T));
return *this;
}
bool operator! ()
{
return !data_;
}
// Access
inline T& operator() (unsigned x, unsigned y)
{
return data_.get()[y * width_ + x];
}
inline T const& operator() (unsigned x, unsigned y) const
{
return data_.get()[y * width_ + x];
}
inline T& operator() (unsigned i)
{
return data_.get()[i];
}
inline T const& operator() (unsigned i) const
{
return data_.get()[i];
}
unsigned int width() const
{
return width_;
}
unsigned int height() const
{
return height_;
}
unsigned int size() const
{
return size_;
}
iterator begin()
{
return iterator(data_.get());
}
iterator end()
{
return iterator(&data_.get()[size_]);
}
// Manipulate
void set(unsigned wset, unsigned hset)
{
width_ = wset;
height_ = hset;
size_ = wset * hset;
if (data_) {
data_.release();
}
data_ = std::unique_ptr<T>(new T[size_]);
}
}; // Array2D
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment