문제

C ++에서 2D 행렬을 어떻게 동적으로 할당합니까? 나는 이미 알고있는 것을 바탕으로 시도했습니다.

#include <iostream>

int main(){
    int rows;
    int cols;
    int * arr;
    arr = new int[rows][cols];
 }

하나의 매개 변수에 대해 작동하지만 이제는 두 가지입니다. 어떻게해야합니까?

도움이 되었습니까?

해결책

매트릭스는 실제로 배열 배열입니다.

int rows = ..., cols = ...;
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
    matrix[i] = new int[cols];

물론 행렬을 삭제하려면 다음을 수행해야합니다.

for (int i = 0; i < rows; ++i)
    delete [] matrix[i];
delete [] matrix;

방금 또 다른 가능성을 알아 냈습니다.

int rows = ..., cols = ...;
int** matrix = new int*[rows];
if (rows)
{
    matrix[0] = new int[rows * cols];
    for (int i = 1; i < rows; ++i)
        matrix[i] = matrix[0] + i * cols;
}

이 배열을 제거하는 것이 더 쉽습니다.

if (rows) delete [] matrix[0];
delete [] matrix;

이 솔루션은 여러 작은 덩어리 대신 모든 요소에 대해 단일 큰 메모리 블록을 할당하는 이점이 있습니다. 내가 게시 한 첫 번째 솔루션은 더 나은 예입니다. 배열의 배열 그러나 개념.

다른 팁

당신은 또한 사용할 수 있습니다 std::vectors 이것을 달성하기위한 :

사용 std::vector< std::vector<int> >

예시:

std::vector< std::vector<int> > a;

  //m * n is the size of the matrix

    int m = 2, n = 4;
    //Grow rows by m
    a.resize(m);
    for(int i = 0 ; i < m ; ++i)
    {
        //Grow Columns by n
        a[i].resize(n);
    }
    //Now you have matrix m*n with default values

    //you can use the Matrix, now
    a[1][0]=1;
    a[1][1]=2;
    a[1][2]=3;
    a[1][3]=4;

//OR
for(i = 0 ; i < m ; ++i)
{
    for(int j = 0 ; j < n ; ++j)
    {      //modify matrix
        int x = a[i][j];
    }

}

노력하다 부스트 :: multi_array

#include <boost/multi_array.hpp>

int main(){
    int rows;
    int cols;
    boost::multi_array<int, 2> arr(boost::extents[rows][cols] ;
}
 #include <iostream>

    int main(){
        int rows=4;
        int cols=4;
        int **arr;

        arr = new int*[rows];
        for(int i=0;i<rows;i++){
           arr[i]=new int[cols];
        }
        // statements

        for(int i=0;i<rows;i++){
           delete []arr[i];
        }
        delete []arr;
        return 0;
     }
arr = new int[cols*rows];

구문을 신경 쓰지 않는다면

arr[row * cols + col] = Aij;

또는 연산자 [] 어딘가에 과부하를 사용하십시오. 이것은 배열 배열보다 캐시 친화적 일 수 있거나 그렇지 않을 수도 있습니다. a) 배열 배열은 솔루션 일뿐 만 아니라 b) 메모리 블록에 매트릭스가있는 경우 일부 작업이 더 쉽게 구현하기가 더 쉽다는 것을 지적하고 싶습니다. 예를 들어

for(int i=0;i < rows*cols;++i)
   matrix[i]=someOtherMatrix[i];

한 줄은 더 짧습니다

for(int r=0;i < rows;++r)
  for(int c=0;i < cols;++s)
     matrix[r][c]=someOtherMatrix[r][c];

이러한 매트릭스에 행을 추가하는 것은 더 고통 스럽습니다

또는 1D 배열을 할당 할 수 있지만 2D 방식으로 참조 요소를 할당 할 수 있습니다.

행 2, 열 3을 다루려면 (왼쪽 상단 코너는 행 0, 열 0) :

ARR [2 * matrix_width + 3

여기서 matrix_width는 연속 요소 수입니다.

배열 배열을 설명하는 다른 답변이 정확합니다.
그러나 배열로 수학적으로 무언가를 계획하고 있거나 희소 행렬과 같은 특별한 것을 필요로한다면 많은 수학 libs와 같은 많은 수학 중 하나를 살펴 봐야합니다. TNT 너무 많은 바퀴를 다시 발명하기 전에

수학 연산자가 필요하지 않은 경우 간단한 행렬로 사용할 수있는이 그리드 클래스가 있습니다.

/**
 * Represents a grid of values.
 * Indices are zero-based.
 */
template<class T>
class GenericGrid
{
    public:
        GenericGrid(size_t numRows, size_t numColumns);

        GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue);

        const T & get(size_t row, size_t col) const;

        T & get(size_t row, size_t col);

        void set(size_t row, size_t col, const T & inT);

        size_t numRows() const;

        size_t numColumns() const;

    private:
        size_t mNumRows;
        size_t mNumColumns;
        std::vector<T> mData;
};


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns);
}


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns, inInitialValue);
}


template<class T>
const T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx) const
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx)
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
void GenericGrid<T>::set(size_t rowIdx, size_t colIdx, const T & inT)
{
    mData[rowIdx*mNumColumns + colIdx] = inT;
}


template<class T>
size_t GenericGrid<T>::numRows() const
{
    return mNumRows;
}


template<class T>
size_t GenericGrid<T>::numColumns() const
{
    return mNumColumns;
}

이중 포인터를 사용하는 것은 실행 속도/최적화와 가독성 사이의 최상의 타협입니다. 단일 배열을 사용하여 매트릭스의 내용을 저장하는 것은 실제로 이중 포인터가하는 일입니다.

다음 템플릿 제작자 기능을 성공적으로 사용했습니다 (예, 오래된 C 스타일 포인터 참조를 사용하지만 변경 매개 변수와 관련하여 호출 측면에서 코드가 더 명확 해집니다. 참고 문헌. 내가 의미하는 바를 볼 수 있습니다) :

///
/// Matrix Allocator Utility
/// @param pppArray Pointer to the double-pointer where the matrix should be allocated.
/// @param iRows Number of rows.
/// @param iColumns Number of columns.
/// @return Successful allocation returns true, else false.
template <typename T>
bool NewMatrix(T*** pppArray, 
               size_t iRows, 
               size_t iColumns)
{
   bool l_bResult = false;
   if (pppArray != 0) // Test if pointer holds a valid address.
   {                  // I prefer using the shorter 0 in stead of NULL.
      if (!((*pppArray) != 0)) // Test if the first element is currently unassigned.
      {                        // The "double-not" evaluates a little quicker in general.
         // Allocate and assign pointer array.
         (*pppArray) = new T* [iRows]; 
         if ((*pppArray) != 0) // Test if pointer-array allocation was successful.
         {
            // Allocate and assign common data storage array.
            (*pppArray)[0] = new T [iRows * iColumns]; 
            if ((*pppArray)[0] != 0) // Test if data array allocation was successful.
            {
               // Using pointer arithmetic requires the least overhead. There is no 
               // expensive repeated multiplication involved and very little additional 
               // memory is used for temporary variables.
               T** l_ppRow = (*pppArray);
               T* l_pRowFirstElement = l_ppRow[0];
               for (size_t l_iRow = 1; l_iRow < iRows; l_iRow++)
               {
                  l_ppRow++;
                  l_pRowFirstElement += iColumns;
                  l_ppRow[0] = l_pRowFirstElement;
               }
               l_bResult = true;
            }
         }
      }
   }
}

위에서 언급 한 유틸리티를 사용하여 생성 된 메모리를 탈신하려면 단순히 반대로 해제해야합니다.

///
/// Matrix De-Allocator Utility
/// @param pppArray Pointer to the double-pointer where the matrix should be de-allocated.
/// @return Successful de-allocation returns true, else false.
template <typename T>
bool DeleteMatrix(T*** pppArray)
{
   bool l_bResult = false;
   if (pppArray != 0) // Test if pointer holds a valid address.
   {
      if ((*pppArray) != 0) // Test if pointer array was assigned.
      {
         if ((*pppArray)[0] != 0) // Test if data array was assigned.
         {
               // De-allocate common storage array.
               delete [] (*pppArray)[0];
            }
         }
         // De-allocate pointer array.
         delete [] (*pppArray);
         (*pppArray) = 0;
         l_bResult = true;
      }
   }
}

이러한 abovemented 템플릿 함수를 사용하는 것은 매우 쉽습니다 (예 :).

   .
   .
   .
   double l_ppMatrix = 0;
   NewMatrix(&l_ppMatrix, 3, 3); // Create a 3 x 3 Matrix and store it in l_ppMatrix.
   .
   .
   .
   DeleteMatrix(&l_ppMatrix);
const int nRows = 20;
const int nCols = 10;
int (*name)[nCols] = new int[nRows][nCols];
std::memset(name, 0, sizeof(int) * nRows * nCols); //row major contiguous memory
name[0][0] = 1; //first element
name[nRows-1][nCols-1] = 1; //last element
delete[] name;

다음은 C ++로 동적 2D 어레이를 할당하는 가장 명확하고 직관적 인 방법입니다. 이 예에서 템플릿이 모든 경우를 다룹니다.

template<typename T> T** matrixAllocate(int rows, int cols, T **M)
{
    M = new T*[rows];
    for (int i = 0; i < rows; i++){
        M[i] = new T[cols];
    }
    return M;
}

... 

int main()
{
    ...
    int** M1 = matrixAllocate<int>(rows, cols, M1);
    double** M2 = matrixAllocate(rows, cols, M2);
    ...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top