Home > Article > Backend Development > Why am I getting incorrect distances when calculating distances between points in a C vector?
Problem Statement:
When calculating distances between points stored in a vector, an incorrect result is obtained, potentially due to improper usage of iterators.
Code Snippet:
<code class="cpp">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; }</code>
Incorrect Output:
0 1 -1 0
Solution:
The issue arises from unknowingly calling the std::distance() function, which operates on iterators. To resolve this, prefix standard library types with std:: and change the distance() function to take references instead.
<code class="cpp">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)); }</code>
Then, call the function using dereferenced iterators:
<code class="cpp">distance(*ii, *jj);</code>
Additional Optimization:
Instead of a typedef, use struct point directly in C as it is no longer necessary to define it as a struct in typedef.
The above is the detailed content of Why am I getting incorrect distances when calculating distances between points in a C vector?. For more information, please follow other related articles on the PHP Chinese website!