Reputation: 1758
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.
Upvotes: 0
Views: 180
Reputation: 463
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.
Upvotes: 0
Reputation: 354979
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).
Upvotes: 2