2016-08-04 2 views
-3

저는 C++을 처음 접했습니다. 다차원 배열을 만들려고합니다. 이 코드의 문제점은 무엇입니까?C++ - 다차원 배열은 어떻게 만듭니 까?

int sorted_array[] = {{2, 3}, 5, 7}; 

이 오류가 발생합니다.

error: braces around scalar initializer for type 'int' 

감사합니다.

+1

C++에서는 일반적으로 원시 배열을 사용하지 않습니다. C++의 다차원 배열은'std :: array , DIM2> sorted_array;'이어야합니다. –

답변

4

다차원 배열을 선언 할 때 첫 번째 것을 제외하고 모든 차원을 지정해야합니다.

동등

int sorted_array[][2] = {{2, 3}, {5}, {7}}; 

가로 :

int sorted_array[][] = {{2, 3}, {5}, {7}}; 

를 컴파일러가 두 번째 차원 2을 추론 할 것으로 예상 :

int sorted_array[3][2] = {{2, 3}, {5}, {7}}; 

당신은 사용할 수 없습니다.

+0

위대한 설명, 고마워요. –

0

다차원 배열을 만드는 여러 가지 방법이 있습니다 :이 배열을 생성

int sorted_array[2][2] = {{2,3},{5,7}}; 

그 두 정수

하지만 난 벡터를 권 해드립니다 것이다 저장 INT의 저장이 개 배열

#include <vector> 
std::vector<std::vector<int> > sorted_array = {{2,3},{5,7}}; 

이것은 동일하지만 벡터에 더 많은 기능이있는 벡터입니다.

같은 방법으로 모두 액세스 할 수 있습니다 :

sorted_array[0][1] = 3; 
+1

'std :: array'는 컴파일 타임에 알려진 고정 된 치수를 사용해야합니다. –

0

다른 대답은 물론 정확하지만, 2 차원 배열을 생성 할 수있는 편리한 방법을 래핑하는 것입니다 언급 할 가치가 플랫 행 주요 다음과 같이 클래스의 std::vector 다음과 같이

template<typename _Ty> 
class matrix { 
    // used to enabled [][] overload on matrix objects 
    class proxy_row_vector { 
    public: 
     proxy_row_vector(std::vector<_Ty>& _vec, std::size_t _cols, std::size_t _row_index) 
      : vec(_vec), cols(_cols), row_index(_row_index) {} 
     const _Ty& operator[](std::size_t col_index) const { 
      return vec[row_index*cols + col_index]; 
     } 
     _Ty& operator[](std::size_t col_index) { 
      return vec[row_index*cols + col_index]; 
     } 
    private: 
     std::vector<_Ty>& vec; 
     std::size_t cols; 
     std::size_t row_index; 
    }; 
public: 
    matrix(std::size_t _rows, std::size_t _cols) 
     : mtx(_rows*_cols), rows(_rows), cols(_cols) {} 
    proxy_row_vector operator[](std::size_t row_index) const { 
     return proxy_row_vector(mtx, cols, row_index); 
    } 
    proxy_row_vector operator[](std::size_t row_index) { 
     return proxy_row_vector(mtx, cols, row_index); 
    } 
    std::vector<_Ty>::const_iterator cbegin() const { 
     return mtx.cbegin(); 
    } 
    std::vector<_Ty>::const_iterator cend() const { 
     return mtx.cend(); 
    } 
    // ... other iterator access methods ... 
private: 
    std::vector<_Ty> mtx; 
    std::size_t rows; 
    std::size_t cols; 
}; 

는 그러면 인덱싱 또는 반복기를 사용하여 소자를 단순히 2 차원 배열을 생성하고 조작 할 수

matrix<int> m(3,3); // default initialises 3x3 matrix of ints 
m[0][0] = 1; // set first row, first column element to 1 
for (auto& el : m) 
    el = 4; // fill m with value 4 

이것의 장점 접근법은 간단한 반복자 지원으로 모든 표준 알고리즘을 사용하여 행렬 요소를 조작 할 수있을뿐 아니라 모든 2D 요소 배열에 대해 편리한 관리 인터페이스를 제공 할 수 있습니다.

참고 : 위의 클래스 matrix 아주 최소한 당신은 더 메소드와 생성자 (경계 체크를위한 같은 at 방법뿐만 아니라 rows() 방법 및 행의 수를 찾는 columns() 방법을 제공 할 분명히 것 , 행렬의 열).