计算c ++中两点之间距离的问题? [英] Problems with calculating distance between two points in c++?

查看:373
本文介绍了计算c ++中两点之间距离的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的有这个恼人的问题。我编写了一个程序,可以实时检测和跟踪对象。现在,我可以看到我跟踪对象的坐标,我的目标是计算跟踪器对象的新位置与前一个位置之间的距离。这就是我做的。比如说,x和y是被跟踪对象的位置。我已将x和y推回到点矢量中,然后我的目标是运行循环来计算距离。但每次我运行它显示的程序,矢量下标超出范围。我该如何解决?



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;
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;
}



}


}

推荐答案

您正在将N值推入向量中。对于每个n< N你从第n个中减去第(n + 1)个值。这意味着当你在第(N-1)次循环时你的向量访问从结束开始并触发异常。



所以改变条件为循环到 i< (cont.size() - 1),问题就会消失。
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.


这篇关于计算c ++中两点之间距离的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆