2

さて、私はいくつかのプログラミング演習を行っていましたが、ファイルの読み取りに関する演習で行き詰まりました。私がする必要があるのは、特定の行のセットを 2D 配列に読み込むことです。行の長さと行の量はさまざまですが、事前に知っています。

したがって、ファイルは次のようにフォーマットされます。

と の 2 つの数値がありますnmここで1 <= n, m <= 20

次のようにフォーマットされたファイルに入っています:n(2つの数字の間にスペースがあります)mn m

その行の後に、それぞれ要素nを持つ整数の行があります。mたとえば、入力は次のようになります: (数値は範囲内にあります)0 <= # <= 50

5 3
2 2 15
6 3 12
7 3 2
2 3 5
3 6 2

このことから、プログラムは 15 個の要素があることを認識し、次のように配列に保持できます。 int foo[5][3]

では、このようにファイルを読み込むにはどうすればよいでしょうか。そして最後に、ファイルには次々と複数の入力セットがあります。したがって、次のようになります: (2, 2 は最初のセットの情報であり、3, 4 は 2 番目の入力セットの情報です)

2 2
9 2
6 5
3 4
1 2 29
9 6 18
7 50 12

この種の入力を C++ のファイルから読み取るにはどうすればよいですか?

4

2 に答える 2

2

まず、ある種のマトリックス/グリッド/2darray クラスが必要です

//A matrix class that holds objects of type T
template<class T>
struct matrix {
    //a constructor telling the matrix how big it is
    matrix(unsigned columns, unsigned rows) :c(columns), data(columns*rows) {}
    //construct a matrix from a stream
    matrix(std::ifstream& stream) {
        unsigned r;
        stream >> c >> r;
        data.resize(c*r);
        stream >> *this;
        if (!stream) throw std::runtime_error("invalid format in stream");
    }
    //get the number of rows or columns
    unsigned columns() const {return c;}
    unsigned rows() const {return data.size()/c;}
    //an accessor to get the element at position (column,row)
    T& operator()(unsigned col, unsigned row) 
    {assert(col<c && row*c+col<data.size()); return data[data+row*c+col];}
protected:
    unsigned c; //number of columns
    std::vector<T> data; //This holds the actual data
};

そして、単純に operator<< をオーバーロードします

template<class T>
std::istream& operator>>(std::istream& stream, matrix<T>& obj) {
    //for each row
    for(int r=0; r<obj.rows(); ++r) {
        //for each element in that row
        for(int c=0; c<obj.cols(); ++c)
            //read that element from the stream
            stream >> obj(c, r);  //here's the magic line!
    }
    //as always, return the stream
    return stream;
}

かなり簡単です。

int main() {
   std::ifstream input("input.txt");
   int r, c;
   while(input >> c >> r) { //if there's another line
       matrix<char> other(c, r); //make a matrix
       if (!(input >> other)) //if we fail to read in the matrix
           break;  //stop
       //dostuff
   }
   //if we get here: invalid input or all done 
}
于 2012-09-18T20:13:20.133 に答える
0

実行時にメモリを動的に割り当てる方法が必要です。実行時に、ファイルから読み取る必要があるデータの量がわかっているからです。これを行うには (少なくとも) 2 つの方法があります。

  1. @MooingDuck の提案に従って std:vector を使用する

  2. newornew[]演算子を使用して配列を動的に割り当てます。deleteまた、 ordelete[]演算子を使用してメモリを解放する必要があります。

于 2012-09-18T20:17:09.320 に答える