[英]size limit of allocation in c++?
我用它在cpp中分配一個2D數組:
int s[n][2];
但是似乎當n非常大(最大為1e6)時,會創建運行時錯誤(退出代碼:11)。
如何解決這個問題呢?
您正在堆棧上進行分配,並且堆棧溢出。
您需要像這樣分配2d數組
int** ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i)
ary[i] = new int[sizeX];
或者更好的是,使用Boost::ublas::matrix
或Eigen Vector2d
,或者如Paul McKenzie所建議的那樣,使用std::vector
(其中最簡單的一種)
那不是動態分配。 另外,如果n
是變量,則它甚至都不是有效的ANSI C ++,因為您不能聲明具有可變數量的條目的數組。
要正確地動態分配,請考慮使用std::vector
。
#include <vector>
//...
// Simulate s[n]
std::vector<std::vector<int>> s(n, std::vector<int>(2));
//..
// You can now use s similar to a 2 dimensional array.
如果出於某種原因,您需要二維數組的數據連續,請考慮以下答案:
這種類型的聲明在堆棧上分配了內存。 可能太大了。 使用REAL動態分配( new int[n]
)。
就像其他人所說的那樣,您遇到的“問題”是因為您沒有使用動態內存分配。
@ {Straight Line}向您展示了一種創建2D數組的類似C的解決方案,而@PaulMcKenzie向您展示了一種使用矢量的解決方案,並提出了連續存儲的問題。 但是,后者是不同的,因為它不限制列的大小(假設[row][col]
索引)。
@dasblinkenlight 的答案向您展示了如何創建自己的2d數組類。 我認為這是C ++的本質,可以定義自己打算如何管理內存,並公開一組可公共訪問的方法來與代碼中的“對象”進行交互。 大小為nxp
2d數組無非是由兩個下標索引的np
元素,所以這就是您應該編寫的代碼。 下面是如何做到這一點的最小示例:
#include <new>
template <class T>
class Array2D
{
public:
Array2D()
: m_ptr(NULL)
{ clear() }
~Array2D()
{ clear(); }
void clear()
{
// free current allocation if any
if (m_ptr)
delete[] m_ptr;
// reset member variables
m_ptr = NULL;
m_nrows = m_ncols = 0;
}
inline unsigned nrows() const { return m_nrows; }
inline unsigned ncols() const { return m_ncols; }
void set_size( unsigned nr, unsigned nc )
{
// clear any previous allocation
clear();
// new allocation
m_ptr = new T[nr*nc];
m_nrows = nr;
m_ncols = nc;
}
// access elements using [row][col]
inline T* operator[] ( unsigned row )
{ return &m_ptr[ row*n_cols ]; }
// access elements using (row,col)
inline T& operator() ( unsigned r, unsigned c )
{ return m_ptr[ c + n_cols*r ]; }
protected:
T *m_ptr;
unsigned m_nrows, m_ncols;
};
如果您知道將要大量使用矩陣,那么您的第一個反應應該是檢查已經存在的矩陣。 有許多成熟的C ++庫實現2d數組(例如,參見此比較 ),處理您不希望自己重新訪問的功能,問題和優化(除非您真的知道自己在做什么,或者您真的需要簡單的東西)。 您只需要找到適合每個特定應用程序的庫即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.