Re: Vector help, subscript out of range, and basic tutoring
On Mar 15, 9:50 pm, yogi_bear_79 <yogi_bear...@yahoo.com> wrote:
Distant learning student. My lab is to write a function to perform
the addition of large integers, with no limit to the number of digits.
(Also have to do a subtraction, division, and multiplication lab). It
is suggested to treat each number as a sequence. This is what I have
so far, this is rough code just to get it working:
1. I can't get the syntax correct on the 'for' statement in the
longAdditon function. No matter what I try I get a run-time error
subscript out of range.
2. Being very much a rookie, I am sure this isn't the prettiest code;
I am open to ideas, hints, etc. Bear in mind that I am basically self
taught here, and more of a systems admin than a programmer.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int longAdditon(vector<int> &vOne, vector<int> &vTwo);
string toStr(int &i);
int main ()
{
vector<int> vOne, vTwo;
string one, two;
int x = 0;
size_t r;
cin>>one;
r = one.length();
for (int x = 0; x < r; x++){
vOne.push_back(int(one[x] - '0'));
}
cin>>two;
r = two.length();
for (int x = 0; x < r; x++){
vTwo.push_back(int(two[x] - '0'));
}
longAdditon(vOne, vTwo);
}
int longAdditon(vector<int> &vOne, vector<int> &vTwo)
{
int sum, carryOver = 0;
string results;
for(size_t x = vOne.size()-1; x >= 0; x--){
Note, because 'x' is of type size_t, it will *never* be less than 0.
As such,
x >= 0 will always be true.
I suggest you look into vector::rbegin() and vector::rend().
Even better would be to use std::transform to add each element of the
two vectors together, then go through the result and take care of the
carryover as a separate operation.
Lastly, you really should wrap the whole thing into a class...
class BigNum {
public:
explicit BigNum( const std::string& s );
std::string print() const;
};
BigNum add( const BigNum& left, const BigNum& right );
Later, when you learn about operator overloading, you can make it so
that someone can use the '+' to add two bigNums, like this:
BigNum x, y;
// put values in them
BigNum z = x + y;
a BigNumber class is a great way to learn the language.