當試圖生成一個隨機數的向量時,我偶然發現一個std :: bad_alloc錯誤。這裏是我的代碼:bad_alloc初始化和填充矢量?
#include "search.h"
#include "gtest/gtest.h"
int _size = 100;
std::vector<int> GetSortedVector(int size){
//init vector
std::vector<int> v(size);
//fill with random numbers
for (std::vector<int>::size_type i=0; i < v.size(); i++)
v.push_back(std::rand()%(2*size));
//return the setup vector
return v;
}
//triggered automatically
TEST(BinarySearch, NonUniqueSorted){
std::vector<int> v = GetSortedVector(_size);//nothing moves farther than this line
}
P.S:我現在使用generate()
,但我還是好奇爲什麼會失敗。
在預留用於循環的情況下,必須進行修改,以檢查對抗能力不大小。 – Kimi
@Kimi對,忘記了。 –
我不認爲檢查'容量'會是一個好主意,因爲據我所知'reserve'被允許*過度分配(即使可能實際上沒有這樣做)。而只是檢查'size'(函數參數)。 –