Reputation: 47
Is it possible to add one or more dimension to an existing array in c++? For example, I have 2 dimensional array, in somewhere I need to add one or more dimension to this array.
Upvotes: 0
Views: 1657
Reputation: 680
No matter what, as poitroae already mentioned, you will need a copy of some sort. This copy however would be sped up a great deal if you simulated 2-D and 3-D arrays with a 1-D array which is why I decided to post an answer in the first place.
In order to simulate 2-D and 3-D arrays with a 1-D array, you can use simple math to index into the array. This lowers memory segmentation making it faster due to having more chache hits. To add a dimension you would simply create another 1-D array with the proper size, and copy in your current data.
I will provide an example when I can find code where I have done this.
EDIT: Apparently the above is not quite what he wants. I will try again below
You have: a 1D array simulating a 2D array.
It seems like you do not want to actually add a whole dimension to the array, just the matrix. (basically resizing from one size to another while retaining data)
So, here is an example:
You have a 3x3 (U=3, V=3) matrix below
Logical Representation:
|3 5 6|
|7 2 5|
|1 0 2|
Physical representation( int[3*3] "matrix")
[3, 5, 6, 7, 2, 5, 1, 0, 2]
--Convert to a 4x4(X = 4, Y = 4)--
int* newMatrix = new int[X*Y];
for(int i = 0; i < Y; i++)
{
for(int k = 0; k < X; k++)
{
//copy from old if it falls in bounds
if(k < U && i < V)
{
newMatrix[i*X + k] = matrix[i*U + k];
}
//Otherwise, zero out
else
{
newMatrix[i*X + k] = 0;
}
}
}
delete [] matrix;
That should give you a 4x4 newMatrix.
Logically:
|3 5 6 0|
|7 2 5 0|
|1 0 2 0|
|0 0 0 0|
Physically:
[3, 5, 6, 0, 7, 2, 5, 0, 1, 0, 2, 0, 0, 0, 0, 0,]
If you use variables like I did, you should be able to write a function that will do this for any matrix as long as you give it accurate parameters (the X and Y dimensions of the matrix)
To go the other way--downsize--it should be a similar set up (double for loop) where you check if you are in bounds and copy over only if you are. And if not, you simply do not copy anything. I will let you write that one.
I hope this is more what you are looking for. I jumped on dimension in the wrong context. Decided to think of an answer more in terms of matrices.
Upvotes: 2
Reputation: 21367
You cannot do this implicitly. You have to create a new array n-dimensional and copy the desired values
int new_array[10][10][10];
// copy using a loop or a std::-function
Upvotes: 0