C++ 从数组中查找最近点

问题描述 投票:0回答:1

您好先生,我真的是初学者。

我尝试使用数组制作表格,例如这样的表格

int array[5][3] = { {A, 200, 400}, {B, 300, 600}, {C, 100, 200}, {D, 200, 100}, {E, 200, 400} };

所以数组输出将是这样的:

| id |  X  |  Y  |
| A  | 200 | 400 | //First Row
| B  | 300 | 600 | //Second Row
| C  | 100 | 200 |
| D  | 300 | 100 |
| E  | 200 | 400 |

在这个案例中我有价值:

int valueid = null; int valueX = 150; int valueY = 170;

所以在这种情况下,表中最近的点是表中到我的值的 ID C。

我的问题是如何从数组表中找到最近的最近点

我知道只能找到单行的 sqrt :

int cx = array[0][1] - valueX;
int cy = array[0][2] - valueY;
int FindClosest = sqrt(cx * cx + cy * cy);

如何在上面的代码中计算数组表中的最近点仅计算第一行的最近点如何从所有行计算并打印结果?

谢谢。

c++ arrays point closest
1个回答
0
投票

标准库有一个算法部分,其中包含经过测试和可重用的常用算法的各种函数。对于您的问题,这将是

std::min_element
。为了使 min_element 以可读的方式工作,请将您的点建模为 Point (类/结构),而不是一些多维整数数组(其中索引用于表示 x 和 y 以及 id)。 对点进行建模后,您可以创建这些点的数组(或向量)。 下一步是通过提供比较函数来让
std::min_element
工作:通常以 lambda 表达式的形式提供。

演示:https://onlinegdb.com/itNV7M3nG

#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#include <iostream>

// Do NOT use `int array[5][3]` thats a semantically meaningless thing
// only showing HOW you are implementing things, but missing the point
// of describing what you are doing. That will make code hard to read

// So lets introduce a struct to represent a point in your array
// and a function to calculate distance between two of your points

struct Point
{
    std::string name;
    int x;
    int y;

    double distance(const Point& other) const
    {
        return std::sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));
    }
};

// https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt
// print Point to output stream
std::ostream& operator<<(std::ostream& os, const Point& point)
{
    os << "`" << point.name << "(" << point.x << "," << point.y << ")`";
    return os;
}

int main()
{
    // resizable array (std::vector)    
    std::vector<Point> points{ { "A", 0, 0 }, { "B", 2, 2 }, { "C", 5, 5 }, { "D", 9, 9 } };

    // The point you want to find the closest point to
    Point somePoint{ "X", 3, 3 };

    // https://en.cppreference.com/w/cpp/algorithm/min_element
    // https://en.cppreference.com/w/cpp/language/lambda
    auto it = std::min_element(points.begin(), points.end(), 
        // Lambda expression : Capture `somePoint` by reference and then make a compare function that compares distance to `somePoint`for two points in the input
        [&](const Point& a,const Point& b) 
        { 
            return a.distance(somePoint) < b.distance(somePoint); 
        });

    // it is now an iterator referencing the closest point to `somePoint`
    std::cout << "Closest point to " << somePoint << " is " << *it << "\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.