Vector out of range exception

I'm trying to do some operator overloading, the function is supposed to add the values at index [i] of two vectors and place the result in the returning vector. The problem is I keep getting a vector out of range, I'm not sure where its going wrong.

this is the overloaded operator I'm working with (relatively new to these):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector<float> operator+(const vector<float>& a, const vector<float>& b){
    unsigned long size;
    vector<float> temp;
    
    if(a.size() >= b.size())
        size = a.size();
    else
        size = b.size();
    
    for(unsigned int i = 0; i < size; i++){
        temp.at(i) = a.at(i) + b.at(i);
    }
    
    return temp;
}


and then I would do something like this in the main:
1
2
3
4
5
6
7
8
9
vector<float> v, v1, v2;

v1.push_back(9.1);
...
v2.push_back(8);
...
    
v = v1 + v2;


but when I try to output the vector v I just get a vector out of range exception, can someone please point me in the right direction
Last edited on
What is the size of this vector, declared at line 3 ?:
 
vector<float> temp;


Is this valid (line 11) ? :
temp.at(i)
Looking at it again I see that I had an empty vector that I was trying to access, which you obviously cant do.
I changed it to this to push the sum of the two into the new vector but I still get the same problem.

1
2
3
4
5
float val;    
for(unsigned int i = 0; i < size; i++){
        val = a.at(i) + b.at(i);
        temp.push_back(val);
    }
You set the size variable equal to the size of the largest vector so inside the loop the smallest vector will throw an exception.
It may be the same problem, but I'm not sure whether it comes from the same cause.

What happens when v1 has fewer elements than v2? and when v1 has more elements than v2? What should the value of size be in each case.
Last edited on
I fixed it, I just wasn't taking everything in to account! As mentioned, when one stack was larger I was trying to add a value from one vector with an empty index from the other. I just threw in some if statements that checked for that and filled the rest of the smaller vector with zeros to match the others size if needed. Thanks for the help all!
Topic archived. No new replies allowed.