[英]bad_alloc exception with vectors in c++
我不是用c ++編程的專家,所以我的問題可能看起來有些愚蠢,但我無法理解我在做什么錯。
我想用指令分配向量
vector <short int> myvec(rowotot * coltot)
為了代表一個矩陣。
在繼續之前,我想驗證我是否有足夠的空間來分配向量。 如果我用
try {
vector <short int> myvec(rowtot * coltot);
}
catch (bad_alloc& ba) {
cert << "ERROR: ";
cerr << ba.what() << endl;
}
然后嘗試修改向量的元素,因為
在此范圍內未聲明myvec
在向量中保存任何值之前,如何對內存進行檢查? 希望我的問題清楚。
一個簡單的解決方案是在try塊外部聲明向量,然后使用std::vector::reserve
在try-catch塊中分配空間。
std::vector<short int> myvec;
try
{
myvec.reserve(rowotot*coltot);
}
catch (const bad_alloc& ba)
{
cerr <<"ERROR: ";
cerr << ba.what() << endl;
}
這將向量置於外部范圍內,但允許分配可捕獲。
如果您需要已經具有rowotot*coltot
元素的向量,則可以使用相同的方法,但可以調用std::vector::resize
創建項,或者創建一個臨時向量並將其分配給myvec
。
std::vector<short int> myvec;
try
{
myvec.resize(rowotot*coltot);
// or
myvec = std::vector<short int>(rowotot*coltot);
}
catch (const bad_alloc& ba)
{
cerr <<"ERROR: ";
cerr << ba.what() << endl;
}
我還將catch (bad_alloc& ba)
更改為catch (const bad_alloc& ba)
因為它首選由const &
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.