如何按距离从点(x1,y1)以升序排列坐标组?

编程入门 行业动态 更新时间:2024-10-10 16:14:26
本文介绍了如何按距离从点(x1,y1)以升序排列坐标组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有 std :: set< std :: pair< float,float>> 它代表地图上的点(2d,x和y值)一个值为x1和y1。如何按照距离点(x1,y1)的升序排序?

I have std::set<std::pair<float,float>> which represents points on map ( 2d , x and y value) and I have one point with values x1 and y1. How to sort set in ascending order by distance from point ( x1,y1) ?

推荐答案

std :: set 是一个有序容器,并且在插入时发生排序,这取决于可以指定的排序标准第二模板参数。所以使用 set 和根据到参考点的距离返回true或false的谓词。

std::set is an ordered container, and ordering happens upon insertion, depending on a sorting criteria which can be specified with a second template argument. So use a set with a predicate which returns true or false based on the distance to the reference point.

struct DistanceCompare { DistanceCompare(const std::pair<float,float>& point) : point_(point) {} bool operator()(const std::pair<float,float>& lhs, const std::pair<float,float>& rhs) const { return distance2(lhs) < distance2(rhs); }; private: float distance2(const std::pair<float,float>& point) const { // calculate distance squared between point and point_ const float x = point.first - point_.first; const float y = point.second - point_.second; return x*x + y*y; } std::pair<float, float> point_; }; .... std::pair<float,float> refPoint = ....; DistanceCompare comp(refPoint); std::set<std::pair<float, float>, DistanceCompare> pointSet(comp);

这足以比较距离的平方,从而避免调用 std: :sqrt 。

It is enough to compare the distance squared, thus avoiding calls to std::sqrt.

更多推荐

如何按距离从点(x1,y1)以升序排列坐标组?

本文发布于:2023-11-30 18:18:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651037.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:升序   坐标   排列   距离

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!