用C++将某些行读取到2D数组中

Reading certain lines into an 2D array with C++

本文关键字:2D 数组 读取 C++      更新时间:2023-10-16

好吧,我正在进行一些编程练习,其中一个练习涉及读取文件。我需要做的是将一组特定的行读入2D阵列,行的长度和行的数量各不相同,但我事先就知道。

因此文件的格式如下:

有两个数字,nm,其中1 <= n, m <= 20

现在nm出现在文件中,格式如下:n 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
9 2
6 5
3 4
1 2 29
9 6 18
7 50 12

如何从C++中的文件中读取这种输入?

首先,您应该有一个某种的矩阵/网格/2d数组类

//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
};

然后您只需重载运算符<lt;

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 
}

您需要一种在运行时动态分配内存的方法,因为这是您知道需要从文件中读取多少数据的时候。有(至少)两种方法可以做到这一点:

  1. 使用@MooingDuck 建议的std:vector

  2. 使用newnew[]运算符动态分配阵列。您还需要确保使用deletedelete[]运算符释放任何内存。