C++ 查找列表中最左边和最右边的点。std::找到正确的方法吗?
我有一个点对象列表(每个对象都具有x、y属性),希望找到最左侧和最右侧的点。我一直在尝试使用find_if来实现它,但我不确定这是一种方式,因为我似乎无法通过一个比较器实例。找到你是不是该走的路?似乎不是。那么,C++ 查找列表中最左边和最右边的点。std::找到正确的方法吗?,c++,stl,find,comparator,C++,Stl,Find,Comparator,我有一个点对象列表(每个对象都具有x、y属性),希望找到最左侧和最右侧的点。我一直在尝试使用find_if来实现它,但我不确定这是一种方式,因为我似乎无法通过一个比较器实例。找到你是不是该走的路?似乎不是。那么,中是否有一种算法可以实现这一点 提前谢谢 #include <iostream> #include <list> #include <algorithm> using namespace std; typedef struct Point{
中是否有一种算法可以实现这一点
提前谢谢
#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;
}
#包括
#包括
#包括
使用名称空间std;
类型定义结构点{
浮动x;
浮动y;
}点;
bool left(点和p1、点和p2)
{
返回p1.x
使用std::min_元素
和std::max_元素
list<Point>::iterator left = std::min_element(points.begin(), points.end(), left);
list<Point>::iterator right = std::max_element(points.begin(), points.end(), left);
如果使用对
而不是自己的点
,则不需要特殊的比较器。在y轴上也会有具有相同x坐标的点的排序,这可能很有用
有多种方法可以插入typedef对点如果您愿意,可以使用自定义行为编写代码>。比如说,
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;
typedef对点;
枚举单位{x,y};
浮点数和运算符*(点和点,Axis单位c)//内积的“特殊情况”
{返回c==x?p.first:p.second;}
我的观点(2.5,6.3);
浮动x_坐标=我的点*x;
更好的方法是使用boost minmax元素:
#包括
...
auto res=boost::minmax_元素(points.begin(),points.end(),left);
我不能谢谢你。必须创建一个结构左{bool operator(){…};成功work@Tom问题似乎是名称left
与某些内容冲突,如果我将函数名称更改为foo
,我不需要函子,但可以直接传递函数。+1如果性能是一个问题,您可以编写自己的算法,在单次传递列表时同时返回一对min/max。
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;
#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;