【问题标题】:How can I use ranges max to find the closest point to another given point?如何使用最大范围来找到离另一个给定点最近的点?
【发布时间】:2022-05-15 03:18:39
【问题描述】:

所以我创建了一个名为point 的结构,它将由两个整数组成。然后,创建了一个名为closest() 的函数,它将一个包含点的std::vector 和另一个point 作为单独的参数。它应该返回该组中的一个点(来自传递的向量中的一个点),该点最接近作为第二个参数传递的那个点。为了计算两个给定点之间的距离,我必须使用欧几里得距离。如何使用std::ranges::max 重写此代码?

#include <vector>
#include <iostream>
#include <math.h>
#include <cfloat>
struct Point
{
    int x;
    int y;
};

double closest(const std::vector<Point>& points, Point originPoint);

double range(int x1, int y1, int x2, int y2);

int main()
{
    std::vector<Point> points = std::vector<Point>(0);

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            Point point = {i, j};
            points.push_back(point);
        }
    }

    std::cout << closest(points, {-1, -1}) << std::endl;

    return 0;
}

double closest(const std::vector<Point>& points, Point originPoint)
{
    double min = DBL_MAX;

    if (points.empty())
    {
        return 0;
    }

    for (auto point: points)
    {
        double current_range = range(originPoint.x, originPoint.y, point.x, point.y);

        min = current_range < min ? current_range : min;
    }

    return min;
}

double range(int x1, int y1, int x2, int y2)
{
    return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
}
  • 与您的问题无关,我建议改为调用range 函数distance,并让它占用2 个Points,而不是4 个ints。

标签: c++ std-ranges


【解决方案1】:
#include <vector>
#include <iostream>
#include <math.h>
#include <cfloat>
#include <functional>
#include <algorithm>

struct Point
{
    int x;
    int y;
};

std::ostream& operator<<(std::ostream &out, const Point &p) {
    out << "Point{" << p.x << ", " << p.y << "}";
    return out;
}

Point closest(const std::vector<Point>& points, Point originPoint);

double range(int x1, int y1, int x2, int y2);

int main()
{
    std::vector<Point> points = std::vector<Point>(0);

    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            Point point = {i, j};
            points.push_back(point);
        }
    }

    std::cout << closest(points, {-1, -1}) << std::endl;

    return 0;
}

Point closest(const std::vector<Point>& points, Point originPoint) {
    return std::ranges::max(points,
        std::ranges::less(),
        [originPoint](Point p) {
            return range(originPoint.x, originPoint.y, p.x, p.y);});
}

double range(int x1, int y1, int x2, int y2)
{
    return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
}

【讨论】:

  • “仅返回类型不同的函数不能重载”
  • @UlanDuishenaliev 这在修复他对clostest 函数的尝试时是相关的吗?
  • 我试图删除最接近的两倍,但随后它向我显示了新错误,我不知道该怎么做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多