I worte a class recently, and found it very basic and useful, so I'd like to share it.
Features:
1. By real, I mean it's not simulated by or wrapped in a Class. The array name is just a pointer.
2. The array can have arbitrary dimension.
3. The entire array is laid out sequentially in memory.
4. Dynamic allocation.
Usage:
Allocating:
1 2 3
|
size_t szs[] = {2,3,4,5}; // declare the size of each dimension.
MyClass **** my_ptr = (MyClass****)DynArrBuilder< MyClass, 4>::arrnew(szs)
// elem type: MyClass, dimension: 4, and size of each dimension: szs[];
|
It achieved exactly the same function as
1 2
|
MyClass **** my_ptr = new MyClass[2][3][4][5];
//This is actually only used by beginners and makes no sense in C++;
|
The array built by DynArrayBuilder does not only look like the same, but is also implemented in exactly the same way.
Access:
e.g. To access an element, you can:
my_ptr[1][2][3][4] = XXX;
or
(***my_ptr)[2*3*4*5 - 1] = XXX;
Or even
(**my_ptr)[2*3*4 - 1][4] = XXX;
This is because each dimension as well as the entire array is laid out sequentially in memory.
So it is just the same as operating an array declared like:
int my_arr[2][3][4][5];
Delete:
When you don