一点一点解读紫书中例子--大整数类BigInteger (1)

首先贴上前一部分代码:

struct BigInteger {
    static const int BASE = 100000000;
    static const int WIDTH = 8;
    vector<int> s;

    BigInteger(long long num = 0) { *this = num; }
    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();
            int start = max(0, end-WIDTH);
            sscanf(str.substr(start, end-start).c_str(), "%d", &x);
            s.push_back(x);
        }
        return *this;
    }
};

这里有几个问题:

  1. *this是什么?
    首先我们得知道 this 是一个指向该结构体的指针,所以 *this = num; 就是为了在使用struct声明变量时对变量进行初始化。
  2. BigInteger operator = (long long);
    个人认为此函数作用不大,因为形参是long long类型,所以一旦程序需要处理的数据大于long long的范围,这样一来此数据就无法准确的传入这个函数,这样一来就不能指望这个函数能给出正确的结果了。
  3. BigInteger operator = (const string);
    我认为这个函数才是最有用的,首先形参是以字符串的形式传入,这样我们就不用担心上面那种情况的出现了。接下来就是对字符串的处理,这里先介绍一下这几个函数:

    sscanf()函数:这里写一个例子,简单理解一下这个函数的作用。

    char s[20];
    sscanf("Helloworld", "%s", s);
    printf("%s", s);
    //输结果是Helloworld

    substr()函数:也写一个例子,简单理解一下:

    string str = "Helloworld";
    string str2 = str.substr(3, 3);
    //str2:low

    c_str()函数:可以看一下https://zhidao.baidu.com/question/104592558.html

现在步入正题:
首先不难看出作者的意图:通过vector s 来分段保存大数据的值,每满8位数存一次,为什么是8位数呢?看了http://blog.csdn.net/mrcrack/article/details/53263235,我就知道对于两个8位数相加可能等于9位数,而int最多只能保存到2147483647,这样一来使用8位数一存就十分保险。

len 表示一共可以分为几个8位数,不足8为按8位计算。

接下来的有了上面那些函数就不难理解了。

你可能感兴趣的:(uva)