Answer the question
In order to leave comments, you need to log in
How to rearrange elements in a 2D array?
How to rearrange elements in a 2D array up to a specific element? Without using std!
Example:
We have a two-dimensional array:
0 1 2
5 8 3
4 4 2
We want to get for n = 8 (counting from 0):
2 4 4
3 8 5
2 1 0 - completely inverted
If n=3 (counting from 0), then we change only the first four elements of the array, i.e. at the output:
5 2 1
0 8 3
4 4 2 - elements from 0 to 3 are swapped (zero to 3, 1 to 2)
Answer the question
In order to leave comments, you need to log in
If the array is on the stack, then this method will do:
const int n = 5;
int arr[3][3] = {0, 1, 2, 5, 8, 3, 4, 4, 2};
int *ptr = reinterpret_cast<int *>(arr);
for(int i = 0, c = (n + 1) / 2; i < c; ++i) {
int tmp = ptr[i];
ptr[i] = ptr[n - i];
ptr[n - i] = tmp;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question