2016-08-04 12 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[3][2] = {{2, 3}, {5}, {7}}; 

あなたが使用することはできません:

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

を第二次元に2を推定するようにコンパイラに期待と同等です

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

+0

すばらしい説明、ありがとう。 –

0

多次元配列を作成するための多くの方法があります。

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

が、これはその店int型2つの整数

の店舗2つの配列のその配列を作成しますが、私はベクトル

#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をラップすることであることを言及する価値があります:この利点を

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 

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次元配列を作成し、要素を次のようにインデックスやイテレータを使用して操作することができますアプローチは単純なイテレーターのサポートで、標準アルゴリズムのいずれかを使用して行列要素を操作することができ、要素の2D配列に便利な管理インターフェースを提供できます。

注:上記のクラスmatrixは非常に最小限であり、あなたは明らかに、このような境界チェックのためat方法だけでなく、rows()方法と行の数を見つけるためのcolumns()方法として、さらにメソッドとコンストラクタを(提供したいと思います、行列の列)。