我具有存儲在格式未知形狀的像如何將逗號分隔數字矩陣放入C++中的動態分配數組中?
-1,4,12,5.7
2.1,3,-10,3.3
7.1,1.11,12,10
若干矩陣I嘗試將矩陣存儲在動態分配的陣列的文件,因爲我不能硬編碼的行和列的數量。對於這一部分,我用指針到指針和一個演示是如下,
#include <iostream>
using namespace std;
int main()
{
// Rather than user input, I need to change this part to deciding the shape of the matrix myself
int row, col;
cout << "Enter row number and column number, separated with a space:\n";
cin >> row >> col;
int** p_p_grid = new int* [row];
for(int i = 0; i < row; i++)
{
p_p_grid[i] = new int[col];
}
// Fill in the entries
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
// (i + 1) * (j + 1) needs to be replaced by true entries in the matrix
p_p_grid[i][j] = (i + 1) * (j + 1);
}
}
return 0;
}
但是,什麼是指定一個個號碼之前決定以逗號分隔的數塊的形狀的有效途徑?而且我該如何在C++中導入CSV結構的矩陣? (出於某種原因,我不希望使用矢量型,所以請關注陣列上)
如果你使用'new []'作爲動態數組,那麼你做錯了。正確的方法是使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。那麼你不必擔心行和列的數量,它將是完全動態的。你甚至可以有不同數量的列的行。這是真的,如果你需要動態數組,你可以使用'std :: vector'。你「想要」或沒有真正重要的IMO,正確的答案是矢量。 –
謝謝,但是如果'vector'沒有被使用,有沒有辦法呢?@JoachimPileborg – Nicholas
順便說一句,當你說'new [] for dynamic arrays you do it wrong it',你是說有更好的方法而不是'new []'或者你是否在我的代碼中提示有任何錯誤?@JoachimPileborg – Nicholas