your programing

2D 배열을 1D 배열에 매핑

lovepro 2020. 10. 9. 11:33
반응형

2D 배열을 1D 배열에 매핑


1D 배열로 2D 배열을 표현하고 싶습니다. 함수는 두 개의 인덱스 (x, y)와 저장할 값을 전달합니다. 이 두 인덱스는 1D 배열의 단일 요소를 나타내며 그에 따라 설정합니다. 1D 배열에 arrayWidth × arrayHeight 크기가 필요하다는 것을 알고 있지만 각 요소를 설정하는 방법을 모르겠습니다.

예를 들어, (2,4,3)과 (4,2,3)을 어떻게 구별합니까? 나는 배열을 x * y로 설정하려고했지만 2 * 4와 4 * 2는 배열에서 같은 지점을 가져 오므로 그것들이 달라야합니다.


배열 요소를 행 순서 또는 열 순서로 저장할지 여부를 결정한 다음 일관성을 유지해야합니다. http://en.wikipedia.org/wiki/Row-major_order

C 언어는 다차원 배열에 행 순서를 사용합니다.

1 차원 배열로이를 시뮬레이션하려면 행 인덱스에 너비를 곱하고 열 인덱스를 추가합니다.

 int array[width * height];

 int SetElement(int row, int col, int value)
 {
    array[width * row + col] = value;  
 }

2D 배열 인덱스를 1D 배열 인덱스로 재 계산하는 일반적인 공식은 다음과 같습니다.

index = indexX * arrayWidth + indexY;

또는 사용할 수 있습니다

index = indexY * arrayHeight + indexX;

( arrayWidthX 축 arrayHeight과 Y 축을 따라 측정 되었다고 가정 )

물론, 대체 고유 한 매핑을 제공하는 다양한 공식을 생각 해낼 수 있지만 일반적으로 그럴 필요는 없습니다.

C / C ++ 언어에서 내장 다차원 배열은 메모리에 저장되므로 마지막 인덱스가 가장 빠르게 변경됩니다. 즉, 다음과 같이 선언 된 배열의 경우

int xy[10][10];

요소 xy[5][3]xy[5][4]메모리에서 바로 뒤에옵니다 . 두 가지 중 "마지막"으로 간주하는 인덱스 (X 또는 Y)에 따라 위의 두 공식 중 하나를 선택하여이 규칙을 따를 수도 있습니다.


예 : SIZE_X 및 SIZE_Y 크기의 2D 배열을 나타내려고합니다. 즉, MAXX 크기의 연속 된 행을 MAXY 개 갖게됩니다. 따라서 설정된 기능은

void set_array( int x, int y, int val ) { array[ x * SIZE_Y + y ] = val; }

얻을 수 있습니다 :

int get_array( int x, int y ) { return array[ x * SIZE_Y + y ]; }

다른 사람들이 C 맵을 행 순서로 말했듯이

   #include <stdio.h>

   int main(int argc, char **argv) {
   int i, j, k;
   int arr[5][3];
   int *arr2 = (int*)arr;

       for (k=0; k<15; k++) {
          arr2[k] = k;
          printf("arr[%d] = %2d\n", k, arr2[k]);
       }

       for (i=0; i<5; i++) {
         for (j=0; j< 3; j++) {
            printf("arr2[%d][%d] = %2d\n", i, j ,arr[i][j]);
         }
       } 
    } 

산출:

arr[0] =  0
arr[1] =  1
arr[2] =  2
arr[3] =  3
arr[4] =  4
arr[5] =  5
arr[6] =  6
arr[7] =  7
arr[8] =  8
arr[9] =  9
arr[10] = 10
arr[11] = 11
arr[12] = 12
arr[13] = 13
arr[14] = 14
arr2[0][0] =  0
arr2[0][1] =  1
arr2[0][2] =  2
arr2[1][0] =  3
arr2[1][1] =  4
arr2[1][2] =  5
arr2[2][0] =  6
arr2[2][1] =  7
arr2[2][2] =  8
arr2[3][0] =  9
arr2[3][1] = 10
arr2[3][2] = 11
arr2[4][0] = 12
arr2[4][1] = 13
arr2[4][2] = 14

행 주요 예제 사용 :

A(i,j) = a[i + j*ld]; // where ld is the leading dimension
                      // (commonly same as array dimension in i)

// matrix like notation using preprocessor hack, allows to hide indexing
#define A(i,j) A[(i) + (j)*ld]

double *A = ...;
size_t ld = ...;
A(i,j) = ...;
... = A(j,i);

It's important to store the data in a way that it can be retrieved in the languages used. C-language stores in row-major order (all of first row comes first, then all of second row,...) with every index running from 0 to it's dimension-1. So the order of array x[2][3] is x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2]. So in C language, x[i][j] is stored the same place as a 1-dimensional array entry x1dim[ i*3 +j]. If the data is stored that way, it is easy to retrieve in C language.

Fortran and MATLAB are different. They store in column-major order (all of first column comes first, then all of second row,...) and every index runs from 1 to it's dimension. So the index order is the reverse of C and all the indices are 1 greater. If you store the data in the C language order, FORTRAN can find X_C_language[i][j] using X_FORTRAN(j+1, i+1). For instance, X_C_language[1][2] is equal to X_FORTRAN(3,2). In 1-dimensional arrays, that data value is at X1dim_C_language[2*Cdim2 + 3], which is the same position as X1dim_FORTRAN(2*Fdim1 + 3 + 1). Remember that Cdim2 = Fdim1 because the order of indices is reversed.

MATLAB is the same as FORTRAN. Ada is the same as C except the indices normally start at 1. Any language will have the indices in one of those C or FORTRAN orders and the indices will start at 0 or 1 and can be adjusted accordingly to get at the stored data.

Sorry if this explanation is confusing, but I think it is accurate and important for a programmer to know.


You should be able to access the 2d array with a simple pointer in place. The array[x][y] will be arranged in the pointer as p[0x * width + 0y][0x * width + 1y]...[0x * width + n-1y][1x * width + 0y] etc.

참고URL : https://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array

반응형