首先,您应该有某种矩阵/网格/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
}