gpt4 book ai didi

c++ - 在看似简单的操作上导致 vector 中的 push_back 出现段错误

转载 作者:行者123 更新时间:2023-11-30 01:00:56 25 4
gpt4 key购买 nike

我正在为 Project Euler 开发一个程序添加 2^1000 的所有数字。到目前为止,我已经能够在程序段错误达到大约 5 位时跟踪程序段错误,并尝试在函数 carry() 的第 61 行将一个 1 推到 vector 上。

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class MegaNumber
{
vector<int> data; //carries an array of numbers under ten, would be char but for simplicity's sake
void multiplyAssign(int operand, int index); //the recursive function called by the *= operator
void carry(int index);//if one of the data entries becomes more than ten call this function
public:
void printNumber(); //does what it says on the can
void operator*=(MegaNumber operand);
void operator*=(int operand);
void operator+=(int operand);
MegaNumber(string);
unsigned long int AddAllDigits();//returns the value of all of the digits summed
};

MegaNumber::MegaNumber(string operand)
{
for(int i= operand.size()-1; i>=0;i--) //run it into the memory smallest digit first
{
data.push_back(operand[i]-48); //converts a text char to an int
}
}

void MegaNumber::printNumber()
{
int temp = data.size();
for(unsigned int i=(temp); i>0;--i)
{
cout << (int)data[i-1];
}
}

void MegaNumber::operator*=(int operand)
{
if(operand > 9)
{
cout << "function does not yet deal with large ints than 9";
}
else multiplyAssign(operand, 0);
}

void MegaNumber::multiplyAssign(int operand, int index)
{
data[index] *=operand;
if(index<data.size()) multiplyAssign(operand, index+1);
if(data[index] > 9) carry(index);
}

void MegaNumber::carry(int index)
{

int temp = (data[index] / 10); //calculate the amount to carry
if(data.size()==index+1)
{
data.push_back(temp);//if there is no upper digit push it onto the stack
}
else
{
data[index+1]+=temp; //else add it to the next digit

if(data[index+1]>9) carry(index+1); //rinse and repeat
}
data[index]-=temp*10; //remove what's been carried
}

unsigned long int MegaNumber::AddAllDigits() //does what it says on the can
{
unsigned long int Dagger = 0;
for(int i=0; i<data.size();i++) Dagger+=data[i];
return Dagger;
}

int main()
{
MegaNumber A("2");
A.printNumber();
cout << "\n";
for(unsigned int i=0; i<20; i++) A*=2;
A.printNumber();
cout << "\n";
cout << A.AddAllDigits() << "\n";
cout << "Hello world!" << endl;
return 0;
}

这可能是什么原因造成的?

最佳答案

multiplyAssign 中检查它是否是有效索引之前使用 data[index]:

data[index] *= operand;
if(index<data.size()) multiplyAssign(operand, index+1);

还使用 '0' 而不是 48。这更容易、更清晰并且更不容易出错。

关于c++ - 在看似简单的操作上导致 vector<int> 中的 push_back 出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1766351/

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