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

标签 c++ arrays file stream

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

因此文件的格式如下:

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/

相关文章:

file - Flutter:保存应用程序常规配置的最佳实践是什么?

c++ - 是否可以将 boost::any 或 boost::variant 与 boost::pool 一起使用?

c++ - 我自己的连接函数不会更改目标字符串

c++ - 如何覆盖 C++ 中的函数

c++ - 无法访问在标准回调中传递的对象变量

c++ - 存储在文件中的记录

javascript - 如何在json文件中添加或插入记录

c - 双指针字符串的大小是多少?

Java动态创建实例变量的对象数组

c++ - 你如何在 C++ 中获取文件?