次のような入力ファイルから始めます。
2 3
2 3 4
4 3 2
このデータをC ++の2D配列(行/列の数を指定する最初の行)に読み込もうとしています。
私のコードは現在次のようになっています:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open ("dataset.in");
// a matrix
int a_numrows;
int a_numcols;
int a[a_numrows][a_numcols];
fin >> a_numrows >> a_numcols;
cout << a_numrows << " " << a_numcols << endl;
for (int i = 0; i<a_numrows; i++)
{
for (int j = 0; j<a_numcols; j++)
{
fin >> a[i][j];
}
}
cout << a[0][0] << endl;
fin.close();
return 0;
}
ただし、2D配列の各行には、最後の行が格納されているように見えます。したがって、a[0][0]
が出力されると、を返します4
。この振る舞いは、他の言語から来るものがうまくいくはずだと私が思う方法ではありません。
これらの行を並べ替える必要があります。
int a[a_numrows][a_numcols];
fin >> a_numrows >> a_numcols;
に
fin >> a_numrows >> a_numcols;
int a[a_numrows][a_numcols];
これは不注意の間違いだと思います。
そうは言っても、2D配列を宣言/使用するためのより安全でより良い方法があります。考えられる例を次に示します。
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream fin("dataset.in");
size_t n_rows, n_cols;
fin >> n_rows >> n_cols;
using T = int;
std::vector<T> array(n_rows * n_cols);
array.assign(std::istream_iterator<T>(fin), std::istream_iterator<T>());
fin.close();
//-----
for (size_t i = 0; i < n_rows; i++)
{
for (size_t j = 0; j < n_cols; j++)
{
std::cout << array[i * n_cols + j] << "\t";
}
std::cout << endl;
}
return 0;
}
出力:
g++ reader.cpp; ./a.out
2 3 4
4 3 2
数値計算を行うときは、一般に、すべての数値を連続したメモリチャンクに格納する方がよいことを覚えておいてください(で行われるようにstd::vector
)。この状況では、コンパイラーがコードをベクトル化する方が簡単です。
コンポーネントにアクセスするには、以下を使用します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加