我将布尔矩阵(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();
答案 0 :(得分: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];