Click here to Skip to main content
16,018,818 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?

C++
int x,y // the position of the tracked object;
vector<Point>cont(0);
Point a;
a = Point(x,y);
cont.push_back(a);
int p,q,r;


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

}
Posted

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