revivedsun
```学习书上的内容，实现了very_long_int类，进行大数加法操作。
char very_long_int::least(size_t i) const
{
if (i < digits.size() && i >= 0)
{
return digits[digits.size()-i-1];
}
return 0;  // 当一个数超出范围，相当令一个数与0相加。
}
---------------------------------------------------------------------------------------

#include <iostream>
#include <vector>
#include <numeric>
#include <cstdlib>
using namespace std;

class very_long_int{
friend ostream& operator<<(ostream& outstream,const very_long_int& very_long);
friend istream& operator>>(istream& instream,very_long_int& very_long);
public:
very_long_int operator+(const very_long_int& other_very_long);
char least(size_t i) const;
private:
vector<char> digits;
};

char very_long_int::least(size_t i) const
{
if (i < digits.size() && i >= 0)
{
return digits[digits.size()-i-1];
}
return 0;
}

very_long_int very_long_int::operator+(const very_long_int& other_very_long)
{
very_long_int sum;
size_t larger_size,partial_sum,carry = 0;
size_t lSize = digits.size();
size_t rSize = other_very_long.digits.size();
larger_size = lSize > rSize ? lSize:rSize;
size_t i;
for (i = 0; i != larger_size;i++)
{
partial_sum = least(i) + other_very_long.least(i) + carry;
carry = partial_sum / 10;
sum.digits.push_back(partial_sum%10);
}
if (carry != 0)
{
sum.digits.push_back(carry);
}
reverse(sum.digits.begin(),sum.digits.end());
return sum;
}

ostream& operator<<(ostream& outstream,const very_long_int& very_long)
{
vector<char>::iterator itr;
const char LOWEST_DIGIT_CHAR = '0';
for (size_t i = 0 ;i != very_long.digits.size(); i++)
{
outstream<<static_cast<int>(very_long.digits[i]);
}
return outstream;
}

istream& operator>>(istream& instream,very_long_int& very_long)
{
const char LOWEST_DIGIT_CHAR = '0';
const char HIGHEST_DIGIT_CHAR = '9';
const char SENTINEL = 'X';
char digit_char = 0;
very_long.digits.erase(very_long.digits.begin(),very_long.digits.end());
while (true)
{
instream>>digit_char;
if (digit_char != SENTINEL)
{
if ( (LOWEST_DIGIT_CHAR<=digit_char) && (digit_char<=HIGHEST_DIGIT_CHAR))
{
very_long.digits.push_back(digit_char - LOWEST_DIGIT_CHAR);
}
}
else
{
break;
}
}

return instream;
}

int main(int argc, char *argv[])
{
very_long_int a,b;
cin>>a>>b;
cout<<endl<<a;
cout<<endl<<b;
cout<<endl<<(a+b)<<endl;
return 0;
}```
0
《数据结构与STL》的全部笔记 4篇