“最简单”的方法是做一些天真的事情,比如完全读取文件一次以获取行/列数,然后再次读取文件以实际将值存储在矩阵中:
unsigned int rows = 0;
unsigned int cols = 0;
std::string line;
while (std::getline(inFile, line)) {
rows++;
std::stringstream ss(line);
std::string col;
while (std::getline(ss, col, ',')) {
cols++;
}
}
// Now allocate the rows*cols matrix
int** matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// and read your values into the matrix ...
// matrix[m][n] = xxx
读取一个文件两次是相当低效的;还有其他方法可以预先获取尺寸。例如,您可以在输入文件中约定在数据之前包含矩阵宽度/高度:
[infile.txt]
3,3
1,2,3
4,5,6
7,8,9
现在您可以读取文件的第一行,并且您会知道该文件的其余部分包含一个 3x3 矩阵。分配你的矩阵new
(类似于上面的例子),然后继续将文件的其余部分读入其中。
Remember清理动态分配的矩阵delete[]
。应该有 1 个电话delete
每次致电new
.
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;