Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ Dynamic 2D Array

Started by Boder Mar 26, 2006 at 2:00 AM 0 replies 500+ views
Original Post
Boder
Boder
Hi, I am trying a nice dynamic 2D array, but I won't know the size at compile time. Is there a way I can uses this notation: array[3][5] or do I have to use array[3*width + 5] ? Thanks
deffer
deffer
Do you mean declaration part, or the accessor part?
I'm guessing the second.

If you only wrap your 2D array into a class, you can use [][] notation. First [] operator would have to return some proxy object, holding specific "row" of the 2D array. The proxy's only functionality would be to have its own [] operator.

Sample:
template<typename T>class Array2d{public:  class row_proxy {    T* rowPtr;  public:    row_proxy(T* p) : rowPtr(p) {};    T& operator[](int x) {      return rowPtr[x];    };  };  class const_row_proxy {    const T* rowPtr;  public:    const_row_proxy(const T* p) : rowPtr(p) {};    const T& operator[](int x) const {      return rowPtr[x];    };  };private:  T* hugeArray;  int rowSize;public:  row_proxy operator[](int y) {    return row_proxy( hugeArray + y*rowSize );  };  const_row_proxy operator[](int y) const {    return const_row_proxy( hugeArray + y*rowSize );  };// ...rest of the class...};

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.