While trying to generate a vector of random numbers I stumble across a std::bad_alloc error. Here’s my code:
#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.: I do use generate() by now, but am still curious why it failed.
v.push_backincreases the size, soi<v.size()is neverfalse.Since your vector is already
sizein length, you need to fill it withor use
reserveinstead:keep the
push_backand check againstsize. I won’t suggeststd::generatebecause you said you’re already doing it like that.