Jump to content
  • Advertisement
Sign in to follow this  
Boder

C++ Dynamic 2D Array

This topic is 4502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
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...
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!