gpt4 book ai didi

c++ - 使用 C++ 将某些行读入二维数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:54:08 25 4
gpt4 key购买 nike

好吧,我正在做一些编程练习,但遇到了一个涉及读取文件的练习。我需要做的是将一组特定的线读入二维数组,线的长度和线的数量各不相同,但我事先知道。

因此文件格式如下:

There are two numbers, n and m, where 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++ 文件中读取这种输入?

最佳答案

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

然后你只需重载运算符<<

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
}

关于c++ - 使用 C++ 将某些行读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12484034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com