0

我将布尔矩阵(ROW*ROW)保存到 .txt 文件(0,1 格式)。

我如何从文件中读取矩阵?我在下面写了代码,但是我将读取的结果与文件进行比较,数组结果与文件不匹配。谁能告诉我哪里写错了?或者有没有更简单的方法来读取矩阵文件?

bool **results = new bool*[ROW];
    for(int i=0;i<ROW;i++){
        results[i] = new bool[ROW];
    }

    ifstream infile;
    infile.open ("FRM.txt");
    string line;
    int row=0;
    if (infile.is_open())
    {
        while ( infile.good() )
        {
            getline(infile,line);
            istringstream iss(line);
            int col=0;
            while(iss)
            {
                string word;
                iss >> word;
                int number = atoi(word.c_str());
                if(number==1){
                    results[row][col] = true;
                }
                else{
                    results[row][col] = false;
                }
                col++;
            } 
            row++;
        }
    }
    infile.close();
4

1 回答 1

1

将矩阵表示为嵌套数组通常是一个坏主意。改用线性数组并通过宏或内联函数进行索引杂耍。

我会去做这样的事情:

#include <algorithm>
#include <cmath>
#include <cstdint> // uint8_t requires C++11
#include <iterator>
#include <vector>

// don't use vector<bool>, it creates all sorts of problems
std::vector<uint8_t> results;
{
  std::ifstream infile('FRM.txt', std::ifstream::in);
  if(infile.is_open() && infile.good())
  {
    std::istream_iterator<uint8_t> first(infile), last;
    copy(first, last, std::back_inserter(results));
  }
}

// only if you know the matrix is square! error checking strongly advised!
size_t nrows = size_t(std::sqrt(results.size()));

// accessing element (i,j) is then as easy as
size_t i = 2, j = 3; // assuming nrows > i,j
bool a_ij = results[i*rows+j];
于 2013-04-08T06:16:33.593 回答