Sign in to follow this  
Boder

C++ Dynamic 2D Array

Recommended Posts

Boder    938
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
deffer    754
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

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