Home > Backend Development > C++ > Why am I getting incorrect distances when calculating distances between points in a C vector?

Why am I getting incorrect distances when calculating distances between points in a C vector?

Linda Hamilton
Release: 2024-11-01 21:06:02
Original
718 people have browsed it

Why am I getting incorrect distances when calculating distances between points in a C   vector?

Correct Utilization of Iterators in 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>
Copy after login

Incorrect Output:

0
1
-1
0
Copy after login

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>
Copy after login

Then, call the function using dereferenced iterators:

<code class="cpp">distance(*ii, *jj);</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template