[英]Finding the left-most and right-most points of a list. std::find_if the right way to go?
I have a list of Point objects, (each one with x,y properties) and would like to find the left-most and right-most points. 我有一个Point对象的列表(每个对象都具有x,y属性),并且想找到最左边和最右边的点。 I've been trying to do it with find_if, but i'm not sure its the way to go, because i can't seem to pass a comparator instance.
我一直在尝试使用find_if进行操作,但是我不确定它的路要走,因为我似乎无法通过比较器实例。 Is find_if the way to go?
是find_if要走的路吗? Seems not.
好像没有。 So, is there an algorithm in
<algorithm>
to achieve this? 那么,
<algorithm>
是否有一种算法可以实现这一目标?
Thanks in advance. 提前致谢。
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
typedef struct Point{
float x;
float y;
} Point;
bool left(Point& p1,Point& p2)
{
return p1.x < p2.x;
}
int main(){
Point p1 ={-1,0};
Point p2 ={1,0};
Point p3 ={5,0};
Point p4 ={7,0};
list <Point> points;
points.push_back(p1);
points.push_back(p2);
points.push_back(p3);
points.push_back(p4);
//Should return an interator to p1.
find_if(points.begin(),points.end(),left);
return 0;
}
Use std::min_element
and std::max_element
instead. 请改用
std::min_element
和std::max_element
。
list<Point>::iterator left = std::min_element(points.begin(), points.end(), left);
list<Point>::iterator right = std::max_element(points.begin(), points.end(), left);
I would also change the signature of left
to: 我还将将
left
的签名更改为:
bool left(const Point& p1, const Point& p2)
If you use pair<float, float>
instead of your own Point
, there's no need for a special comparator. 如果使用
pair<float, float>
代替自己的Point
,则不需要特殊的比较器。 There would also be an ordering on the y-axis of points with the same x-coordinate, which can be useful. 在具有相同x坐标的点的y轴上也将有一个排序,这很有用。
There are various ways to imbue typedef pair<float, float> Point;
有多种方法可以使
typedef pair<float, float> Point;
with custom behavior, if you're so inclined. 具有自定义行为(如果您愿意)。 For example,
例如,
typedef pair<float, float> Point;
enum AxisUnit { x, y };
float &operator*( Point &p, AxisUnit c ) // "special case" of inner product
{ return c == x? p.first : p.second; }
Point my_point( 2.5, 6.3 );
float x_coord = my_point * x;
even better would be to use the boost minmax element: 更好的方法是使用boost minmax元素:
http://www.boost.org/doc/libs/1_42_0/libs/algorithm/minmax/index.html http://www.boost.org/doc/libs/1_42_0/libs/algorithm/minmax/index.html
#include <boost/algorithm/minmax_element.hpp>
...
auto res = boost::minmax_element(points.begin(), points.end(), left);
std::cout << "min: " << res.first << std::endl;
std::cout << "max: " << res.second << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.