问题描述
我想计算两点之间的距离。这两点我存储在一个向量在C ++:(0,0)和(1,1)。
I'm trying to calculate the distance between two points. The two points I stored in a vector in C++: (0,0) and (1,1).
我应该得到结果为
0
1.4
1.4
0
但我得到的实际结果是
0
1
-1
0
我认为方式我在向量中使用迭代器。
我如何解决这个问题?
I think there's something wrong with the way I use iterator in vector.How can I fix this problem?
我发布了下面的代码。
typedef struct point {
float x;
float y;
} point;
float distance(point *p1, point *p2)
{
return sqrt((p1->x - p2->x)*(p1->x - p2->x) +
(p1->y - p2->y)*(p1->y - p2->y));
}
int main()
{
vector <point> po;
point p1; p1.x = 0; p1.y = 0;
point p2; p2.x = 1; p2.y = 1;
po.push_back(p1);
po.push_back(p2);
vector <point>::iterator ii;
vector <point>::iterator jj;
for (ii = po.begin(); ii != po.end(); ii++)
{
for (jj = po.begin(); jj != po.end(); jj++)
{
cout << distance(ii,jj) << " ";
}
}
return 0;
}
推荐答案
可能是因为你有一个在某处使用命名空间std
。 (否则向量
必须是 std :: vector
。),为什么这是一个好主意)。
But rather than doing this, I suggest you change your function so that it takes references instead (see this answer for why that's a good idea anyway.) :
float distance(const point& p1, const point& p2)
{
return sqrt((p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y));
}
注意这些点是由 const
引用。这向调用者指示该函数不会改变它被传递的点。
Note that the points are taken by
const
references. This indicates to the caller that the function won't change the points it is passed.
然后你可以这样调用:
distance(* ii,* jj)
。
Then you can call it like this:
distance(*ii,*jj)
.
在旁注,
typedef struct point {
float x;
float y;
} point;
是C ++中不必要的C-ism。只是拼写
is a C-ism unnecessary in C++. Just spell it
struct point {
float x;
float y;
};
如果
struct
定义从C编译器解析(代码必须参考 struct point
然后,不是简单地点
) ,但我猜测 std :: vector
等将是一个更大的挑战C编译器反正。
That would make problems if this
struct
definition ever was to parse from a C compiler (the code would have to refer to struct point
then, not simply point
), but I guess std::vector
and the like would be far more of a challenge to a C compiler anyway.
这篇关于如何使用迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!