Click here to Skip to main content
15,794,275 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am really having this irritating problem. I have written a program where a object is detected and tracked in real time. Now, i can see the coordinates of the my tracked object and my goal is to calculate the distance between the new position of the tracker object from the previous one. This is what i did. Say, x and y are the positions of the tracked object. I have pushed back x and y into a point vector and then my goal is to run a loop to calculate the distance. But everytime i run the program it shows, vector subscript out of range. How do i fix it?

int x,y // the position of the tracked object;
Point a;
a = Point(x,y);
int p,q,r;

for(int i= 0; i <cont.size(); i++)
  p = pow(( -,2));
  q = pow(( -,2));
  r = sqrt(p+q);
cout<<"The distance is:"<<r<<endl;


1 solution

You're pushing N values into your vector. For every n < N you're subtracting the (n + 1)th value from the nth. This means that when you do your loop for the (N - 1)th time your vector access falls off the end and triggers the exception.

So change the conditional in the loop to i < ( cont.size() - 1 ) and the problem will go away.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900