Updated recommendation:
It's worth noting that boost already did that. So I'll just stick to it, if it isn't meant to be encapsulated in a class.
Original answer:
In general, using raw arrays and allocations is inferior to using std::vector
. Now, you can of course use vector<vector<T>>
, but that's not only lenghty to type, but can also involve unnecessary copying.
Using ptr_vector
or vector<unique_ptr<vector<int>>
would solve the second problem, but complicate the matters even worse. So how to solve it?
It's simple: Don't use 2D arrays at all.
Imagine your 2D array in memory:
[X|X|X|X]
[Y|Y|Y|Y]
[Z|Z|Z|Z]
It's obvious enough that it could be put in one row:
[X|X|X|X|Y|Y|Y|Y|Z|Z|Z|Z]
Now we're back to old, familiar 1D array (doesn't matter if it's a vector
or C-style array). In order to get to your element, you have to know the width of your initial array, and go to the array element corresponding to n'th row, then plainly add the number of columns:
int& access (unsigned x, unsigned y) {
return data[x * sizeY + y]; // Or (y * sizeX + x)
}
Since it's a stub method, you might have a problem in actual usage. Here's an example of a global implementation:
int& accessVectorAs2d (std::vector<int> & data, unsigned x, unsigned y, unsigned int sizeY); // inside stays the same
unsigned SizeX = 20, SizeY = 20;
std::vector<int> V (SizeX * SizeY, 0);
accessVectorAs2d(V, 1, 3, SizeX) = 5;
Reference is returned to allow using your 1D structure in a very similar way to normal 2D array:
// So you can do either reads
int X = access(1, 3);
// Or writes!
access(1,3) = 5;
Additional note: if you'll construct your own class, overloading operator()
can give you even better results:
Data(1, 3) = 5;
int X = Data(1, 3);
Now how you're gonna implement that access (subclassing or encapsulating vector, or just using plain global function) doesn't really matter.
I'd strongly suggest you used std::vector
here. It will ensure no memory will leak (forgotten delete), it will be easier to change the size (either by .push_back()
or .reserve()
) and is in general suggested practice; you're writing in C++, not in C, after all.
Behold! Dragons after this point!
Actually the class should of course be templated, with not only the type, but also number of dimensions (okay, that can be simplified) and size of (every-1) dimension (-1 to allow unlimited growth in one side). This would be probably done best by creating appropriate access functions at compile time, calculating
Sumi = 0i < n (Sizei)i * Di,
where n is number of dimensions, S is an array of dimension sizes, and D is an array of coordinates.