Bad_alloc when initializing and populating a vector?

While trying to create a random number vector, I came across an error std :: bad_alloc. Here is 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
}

PS: I really use generate(), but I'm still wondering why this failed.

+5
source share
2 answers

v.push_backincreases in size, therefore i<v.size()never false.

Since your vector is already long size, you need to fill it

for (std::vector<int>::size_type i=0; i < v.size(); i++)
    v[i] = std::rand()%(2*size);

or use reserveinstead:

std::vector<int> v;
v.reserve(size);

save push_backand check the box size. I will not offer std::generate, because you said that you are already doing this.

+8
source

Go to the next part:

for (std::vector<int>::size_type i=0; i < v.size(); i++)
        v.push_back( std::rand()%(2*size) );

, push_back(), 1. , i < v.size() false, , . - size() , :

for (std::vector<int>::size_type i=0, s = v.size(); i < s; i++)
        v.push_back( std::rand()%(2*size) );
+2

All Articles