'How can I use ranges max to find the closest point to another given point?
So I've created a structure called point that will consist of two integers. Then, created a function called closest() that's going to take an std::vector containing points, and another point, as a separate argument. It should return a point from that group (one of the points from the passed vector) that is closest to the one passed as the second argument. For calculating distance between two given points I have to use Euclidean distance. How I can rewrite this code using 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));
}
Solution 1:[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));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
