Vectors

Hi

I have the following code below. however it crashes. The problem seems to be the i+1 part in line 4. How do I go about fixing this? Tried j=i+1 and tried making a second loop but still did not help. Any suggestions?

1
2
3
4
5
6
7
for (int i=0; i<myVector.size(); i++)
    {
    product1 = myVector[i][6] * myVector[i][7];
    product2 = myVector[i+1][6] * myVector[i+1][7];

    double product = 0.5*(product1 + product2);
    cout << product << endl;
for (int i=0; i<myVector.size(); i++)

If you have a vector which has a size of 10, this means that indexes 0-9 will be valid.

Your for loop will loop to where 'i' is between 0-9. Therefore, i will always be a valid index in this loop.

However... i+1, when i=9 will be out of bounds because 10 is not a valid index.


To fix this... you just have to make sure you never use an out-of-bounds index. Exactly how you do that depends on what you're trying to do.

One way to do it would be to start i at 1, rather than 0... and use i-1 as an index:

1
2
3
4
for (int i=1; i<myVector.size(); i++)
    {
    product1 = myVector[i-1][6] * myVector[i-1][7];
    product2 = myVector[i][6] * myVector[i][7];


This way, you will never go out of bounds, because i will always be less than the size... and i-1 will always be greater than or equal to zero. So both are always in bounds.
Makes sense and works. Thanks!
Topic archived. No new replies allowed.