tags:

views:

63

answers:

2

I wrote a function to take in a vector, a int position and a int value

void add(vector<int>& pro, int pos, int val){
    pro[pos] += val;
    while(pro[pos] > 9){
        int carry = pro[pos]/10;
        pro[pos] %= 10;
        pos++;
        pro[pos] += carry;
    }//while
}//function add

lets say i have

vector<int> list1,list2,product;
list1.push_back(4);
list1.push_back(9);
list1.push_back(9);
list2.push_back(3);
list2.push_back(4);

vector<int>::reverse_iterator i,j;
        int k,l;
        for(j = list2.rbegin(), k = 0; j != list2.rend(); j++,k++){
            for(i = list1.rbegin(), l = 0; i != list1.rend(); i++,l++){
                              add(product, k+l, (*j * *i) );
                        }//for i
                }//for j

but its giving me an error after i execute it saying that "vector subscript out of range"

I'm not sure where this is coming from am I doing something wrong in my add function? Any help is appreciated. Thanks.

+2  A: 

You haven't shown the the product vector; does it have a sufficient number of elements in it? If not, then using pro[pos] in the function certainly won't work.

It would be cleaner not to mix iterators and indices when iterating over the containers; if you need the indices, you should just use indices; this would make the code cleaner and easier to follow (or, if you really want to use iterators, you could use std::distance() to compute the indices from iterators).

James McNellis
eNetik
@eNetik: If you're starting from the end, you'd need to start from `list1.size() - 1` because indexing starts at zero.
James McNellis
A: 

You probably don't have enough space in the product verctor. Do you allocate it ?

I can see from your code that you are trying to implement BigInteger. Have you considered using an existing implementation ?

In order for this to work without pre-allocation, I'd separate the product to two steps.

  1. One without the carry computation. that way you can use push_back
  2. Compute all carries and get the final result
uvgroovy