我想聲明一個沒有初始大小的2D數組。它不斷給我一個錯誤:動態分配一個數組
Error C2078: too many initializes.
我試圖動態分配我的數組,但沒有任何工作,因爲我不太熟悉動態分配。我的問題是如果有一種可能的方式來聲明一個沒有初始大小的數組,如果是的話,最有效的方法是什麼?
我想聲明一個沒有初始大小的2D數組。它不斷給我一個錯誤:動態分配一個數組
Error C2078: too many initializes.
我試圖動態分配我的數組,但沒有任何工作,因爲我不太熟悉動態分配。我的問題是如果有一種可能的方式來聲明一個沒有初始大小的數組,如果是的話,最有效的方法是什麼?
my question is If there is a possible way to declare an Array without an initial size and if so what is the most efficient way to do it ?
當然,你可以提供向量來表示一個二維數組的向量(假設整數值):
std::vector<std::vector<int>> my2DArray;
嗯,關於效率也許性能和內存碎片明智的做法是用一個允許2D座標訪問的接口在內部保存一維矢量。
這將需要您知道並指定尺寸限制。
所以,如果你真的想保持一個2D結構沒有初始大小上面提到的載體向量是要走的路。
我寫了一個簡單的程序,使用指針,新的和刪除功能。您可以添加更多功能。
#include <iostream>
using namespace std;
int main()
{
int size;
cout << "Input size of 2D array : ";
cin >> size;
int *ptr; // Declare Pointer
ptr = new int[size*size]; // Allocate memory of all elements in 2D array
for (int i = 0; i < size*size; i++) {
*(ptr + i) = 0; // Initialize every element to 0
}
cout << "Printing the 2D Array" << endl << endl;
int iterSize = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout << *(ptr + iterSize) << " ";
}
cout << endl;
}
delete [] ptr; // ptr memory is released
return 0;
}
這裏是0輸出初始化所有元素:
'cout << *(ptr + i + j)<<「」;'是錯的 –
感謝您注意@MikeVine,我通過添加一個新變量iterSize –
_ 「什麼是最有效的方式做到這一點?」 _使用['的std :: VECTOR']( http://en.cppreference.com/w/cpp/container/vector)。 – user0042
請包括您迄今嘗試過的代碼。 – brownKnight
嘗試查看「矢量」。如果需要,你可以自己做一個自定義的。 – JustinJmnz