我有一個簡單的程序,試圖將二維數據讀入堆分配的浮點數組中。該計劃如下。讀取二維表到數組
#include <iostream>
#include <fstream>
void read_file(std::ifstream &inFile, float **arr, unsigned m, unsigned n)
{
for(unsigned i = 0; i < m; ++i) {
for(unsigned j = 0; j < n; ++j) {
inFile >> arr[i][j];
std::cout << arr[i][j];
}
std::cout << std::endl;
}
}
int main() {
const unsigned m = 20;
const unsigned n = 1660;
float **A = new float *[m]; // alloc pointers to rows 1,...,m
for(unsigned row = 0; row < m; row++) A[row] = new float [n]; // alloc columns for each row pointer
std::ifstream inFile("data.dat");
read_file(inFile, A, m, n);
// DEALLOC MEMORY
for(unsigned row = 0; row < m; row++) delete [] A[row]; // dealloc columns for each row pointer
delete [] A; // dealloc row pointers
return EXIT_SUCCESS;
}
的數據是0-1條目表(見這裏:data),其是很好的行取向,並且具有20行和1660列。我將打印添加到read_file
函數中以查看錯誤,並且僅打印零,但至少打印正確的數量(20 * 1660個零)。
數據似乎是製表符分隔的;是問題還是我的方法完全無效?
有趣的選擇如何'VECTOR',你不使用它! –
我從'vector'開始,但後來我試着去了解'new'關鍵字。 – ELEC
這是一個不錯的[C++書籍]列表(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。我建議你看看它。對於* 2D陣列*使用矢量向量。 – 2016-12-30 10:05:17