How to work around a very large 2d array in C++ How to work around a very large 2d array in C++ arrays arrays

How to work around a very large 2d array in C++


You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See C++ FAQ Lite for an example of using a "2D" heap array.

int *array = new int[800*800];

(Don't forget to delete[] it when you're done.)


Every post so far leaves the memory management for the programmer. This can and should be avoided. ReaperUnreal is darn close to what I'd do, except I'd use a vector rather than an array and also make the dimensions template parameters and change the access functions -- and oh just IMNSHO clean things up a bit:

template <class T, size_t W, size_t H>class Array2D{public:    const int width = W;    const int height = H;    typedef typename T type;    Array2D()        : buffer(width*height)    {    }    inline type& at(unsigned int x, unsigned int y)    {        return buffer[y*width + x];    }    inline const type& at(unsigned int x, unsigned int y) const    {        return buffer[y*width + x];    }private:    std::vector<T> buffer;};

Now you can allocate this 2-D array on the stack just fine:

void foo(){    Array2D<int, 800, 800> zbuffer;    // Do something with zbuffer...}

I hope this helps!

EDIT: Removed array specification from Array2D::buffer. Thanks to Andreas for catching that!


Kevin's example is good, however:

std::vector<T> buffer[width * height];

Should be

std::vector<T> buffer;

Expanding it a bit you could of course add operator-overloads instead of the at()-functions:

const T &operator()(int x, int y) const{  return buffer[y * width + x];}

and

T &operator()(int x, int y){  return buffer[y * width + x];}

Example:

int main(){  Array2D<int, 800, 800> a;  a(10, 10) = 50;  std::cout << "A(10, 10)=" << a(10, 10) << std::endl;  return 0;}