多次元配列のC++サポートは、ライブラリ(ブーストなど)によって行われます。クラスがなければ、実際には1D配列しか理解できません。特にC/C++が実際には配列の最初の要素へのポインタとして見えるポインタを使用しているときはそうです。あなたの例がクラスなしで動作するようにするには、1つの行を保持する型を定義し、その型の配列を作成する必要があります。
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
typedef int row_t[5];
row_t *arr = new row_t[4] {{3, 6, 9, 23, 16},
{24, 12, 9, 13, 5},
{37, 19, 43, 17, 11},
{71, 32, 8, 4, 7}};
cout<< arr[1][3] << endl<< endl;
int *x = new int;
*x = arr [2][1];
cout<< x<< endl;
cout<< *x<< endl << endl;
*x = arr [0][3];
cout<< x<< endl;
cout<< *x<< endl;
delete x;
delete [] arr;
return 0;
}
また、あなたのように1次元アレイ上に2次元配列を投写することができますブーストのようなものを使用して動的データを2次元のインデックスを取得するには
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int *arr = new int[20] {3, 6, 9, 23, 16,
24, 12, 9, 13, 5,
37, 19, 43, 17, 11,
71, 32, 8, 4, 7};
cout<< arr[5*1+3] << endl<< endl;
int *x = new int;
*x = arr [5*2+1];
cout<< x<< endl;
cout<< *x<< endl << endl;
*x = arr [5*0+3];
cout<< x<< endl;
cout<< *x<< endl;
delete x;
delete [] arr;
return 0;
}
:: multi_array
演算子を使用して
#include <iostream>
#include <boost/multi_array.hpp>
using namespace std;
int main() {
boost::multi_array< int, 2 >arr(boost::extents[4][5]);
int tmp[] { 3, 6, 9, 23, 16,
24, 12, 9, 13, 5,
37, 19, 43, 17, 11,
71, 32, 8, 4, 7 };
arr = boost::multi_array_ref< int, 2 >(&tmp[0], boost::extents[4][5]);
cout<< arr [1][3]<< endl << endl;
int *x = new int;
*x = arr [2][1];
cout<< x<< endl;
cout<< *x<< endl << endl;
*x = arr [0][3];
cout<< x<< endl;
cout<< *x<< endl;
delete x;
// delete [] arr;
return 0;
}
私はコードを正しく、明らかに投稿する方法も知らないです。 – user9076567
推奨読書:https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr – user0042
このコードで何をしたいですか?あなたはすべてを非常に複雑にする 'new'を使用しています。メモリを '削除 'してからアクセスし、再度' delete'します。非常に壊れました。そして、 'return'を書いたのは、' int'を '返す 'か、' return'を完全に残す必要があるので、コンパイルすべきではありません。 – nwp