gpt4 book ai didi

c++ - bad_alloc 在初始化和填充 vector 时?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:01 30 4
gpt4 key购买 nike

在尝试生成随机数 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
}

附注:我现在确实在使用 generate(),但我仍然很好奇为什么它会失败。

最佳答案

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

因为你的 vector 已经是size在长度上,你需要用

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

或使用 reserve相反:

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

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

关于c++ - bad_alloc 在初始化和填充 vector 时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14467597/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com