Sign in to follow this  

C++ Dynamic 2D Array

This topic is 4283 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
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

This topic is 4283 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this