初始化和填充向量时bad_alloc?

Den*_* S. 5 c++ memory-management exception vector

在尝试生成随机数的向量时,我偶然发现了std :: 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
}
Run Code Online (Sandbox Code Playgroud)

PS:我现在使用generate(),但仍然很好奇为什么它失败了.

Luc*_*ore 8

v.push_back增加大小,所以i<v.size()永远不会false.

由于你的矢量已经很size长,你需要填充它

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

或使用reserve:

std::vector<int> v;
v.reserve(size);
Run Code Online (Sandbox Code Playgroud)

保持push_back并检查size.我不会建议,std::generate因为你说你已经这样做了.