今天翻紫书的时候,看到这么一串代码(部分):
(因为我看的是代码片段,可能因为我不了解里面的原理所以有疑问,完整代码在紫书的 124 页)
struct BigInteger{
static const int BASE=100000000;
static const int WIDTH=8;
vector<int> s;
BigInteger operator = (long long num)
{
s.clear();
do{
s.push_back(num%BASE);
num/=BASE;
}while(num>0);
return *this;
}
BigInteger operator = (const string& str){
s.clear();
int x,len=(str.length()-1)/WIDTH+1;
for(int i=0;i<len;i++)
{
int end=str.length()-i*WIDTH;
int start=max(0,end-WIDTH);
sscanf(str.substr(start,end-start).c_str(),"%d",&x);
s.push_back(x);
}
}
};
常量 base,width 是干什么的?为什么要以 108 为标准?
在第一个重载 = 运算符的函数中,若 num=1234,则 do-while 循环完过后,vector 类型的 s 里面只有一个 1234,所以这段代码是错误的吗?
在第二个重载 = 运算符的函数中,sscanf 让 x 以 int 类型从 str.substr(start,end-start).c_str() 中读入,x 不会爆掉吗?