C++:程序在矢量填充和搜索过程中失败
C++ : Program fails during vector filling and searching
我正在练习C++ vector
,作为一项练习,我想用1600万个随机数填充一个向量,然后找到一个数字第一次出现的位置。到目前为止,我实现的代码是:
int getIndexOf(std::vector<int>& v, int num) {
for(std::size_t i=0; i < v.size(); i++) {
if(v.at(i) == num) {
return i;
}
}
return -1;
}
int main() {
int searchedNumber = 42;
int vectorSize = 16000000;
std::vector<int> v(vectorSize);
for(std::size_t i=0; i < v.size(); i++) {
v.push_back(rand() % 10000000);
}
//Linear search
auto start = std::chrono::high_resolution_clock::now();
int position = getIndexOf(v, searchedNumber);
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);
std::cout << "The linear search took: " << duration.count() << " seconds" << std::endl;
std::cout << "The number " << searchedNumber << " occur first at position " << position << std::endl;
return 0;
}
此外,我测量时间只是为了一些统计数据。问题是程序崩溃,出现错误bad_alloc,我将其链接到堆栈空间不足。因此,最初我认为,当向量在堆栈上时,用这么多数字填充向量将是崩溃的原因,我动态地创建了向量(指针(。然而,我仍然会遇到同样的错误。这可能是什么原因?
int vectorSize = 16000000;
std::vector<int> v(vectorSize);
for(std::size_t i=0; i < v.size(); i++) {
v.push_back(rand() % 10000000);
}
这部分不好。push_back()
将一个元素添加到向量中,因此它增加了size()
。因此,这个循环不会终止,直到发生不好的事情。
你应该这样做:
int vectorSize = 16000000;
std::vector<int> v;
v.reserve(vectorSize); // allocate memory without actually adding elements
for(int i=0; i < vectorSize; i++) { // use the known size
v.push_back(rand() % 10000000);
}
相关文章:
- 是否删除在对象构造过程中创建的对象
- 如何在鼠标挂钩过程中检测拖动
- 按边长度递归搜索图中所有可行路径
- clang 插件:在编译过程中修改 AST
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- Adafruit 羽毛RFM69HCW在使用过程中会冻结,需要硬重置
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 线程过程中的线程同步问题
- MySQL 连接器/C++.尝试在此过程中停止连接到数据库
- 将值存储在带有C++的二叉搜索树中
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- 为什么"/usr/include"不在 GCC 默认搜索路径中
- 在调用过程中删除 std::函数
- 动态矩阵特征分解过程中的误差
- cmake在构建过程中使用另一个工具检测标志
- 在模板参数推导过程中丢失限定符