[英]I keep getting a std::bad_alloc error in C++
So I am making a program for Project Euler #14 and I have this所以我正在为 Project Euler #14 制作一个程序,我有这个
#include <iostream>
#include <vector>
using namespace std;
vector <int> CollatzSequence (int n)
{
vector <int> numbers;
int currentNumber = n;
while (currentNumber != 1) {
numbers.push_back(n);
if (currentNumber%2 == 0) {
currentNumber /= 2;
} else {
currentNumber *= 3;
currentNumber += 1;
}
}
numbers.push_back(1);
return numbers;
}
int main()
{
int largestNumber = 0;
int currentNumber = 2;
while (currentNumber < 1000000) {
if (CollatzSequence(currentNumber).size() > largestNumber) {
largestNumber = currentNumber;
}
currentNumber++;
}
cout << largestNumber;
return 0;
}
But I keep getting this error但我不断收到此错误
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
I am new to C++ but I don't know what this error means or how to fix it.我是 C++ 的新手,但我不知道这个错误是什么意思或如何修复它。 Does anyone know how to fix this?
有谁知道如何解决这一问题?
std::bad_alloc
is thrown when allocation of memory fails, in your code this happens when allocating memory for std::vector
returned.当分配 memory 失败时抛出
std::bad_alloc
,在您的代码中,当为返回的std::vector
分配 memory 时会发生这种情况。 std::vector
requires contiguous memory, in your code, the size to be allocated might be causing the problem. std::vector
需要连续的 memory,在您的代码中,要分配的大小可能会导致问题。
as @WhozCraig said in the comments, the function has no need to return the vector itself since only the size is used rather, simply add a counter inside the function and return that.正如@WhozCraig 在评论中所说,function 不需要返回向量本身,因为只使用了大小,只需在 function 内添加一个计数器并返回它。
#include <iostream>
#include <vector>
using namespace std;
int CollatzSequence(int n)
{
int currentNumber = n;
int counter = 0;
while (currentNumber != 1) {
++counter;
if (currentNumber%2 == 0) {
currentNumber /= 2;
} else {
currentNumber *= 3;
currentNumber += 1;
}
}
++counter;
return counter;
}
int main()
{
int largestNumber = 0;
int currentNumber = 2;
while (currentNumber < 1000000) {
if (CollatzSequence(currentNumber) > largestNumber) {
largestNumber = currentNumber;
}
currentNumber++;
}
cout << largestNumber;
return 0;
}
maybe also consider moving from int
to std::uint64_t
like @Pablochaches suggested in the comments也许还可以考虑从
int
移动到std::uint64_t
就像评论中建议的@Pablochaches
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.