1

我有一个 Point 对象列表(每个对象都有 x,y 属性),并且想找到最左边和最右边的点。我一直在尝试用 find_if 来做,但我不确定它要走的路,因为我似乎无法传递比较器实例。find_if 是要走的路吗?似乎没有。那么,是否有一种算法<algorithm>可以实现这一点?

提前致谢。

#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;
}
4

3 回答 3

3

使用std::min_elementandstd::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);

我还将签名更改left为:

bool left(const Point& p1, const Point& p2)
于 2010-04-16T08:36:10.177 回答
0

如果您使用pair<float, float>而不是自己的Point,则不需要特殊的比较器。在具有相同 x 坐标的点的 y 轴上也会有一个排序,这可能很有用。

typedef pair<float, float> Point;如果您愿意,有多种方法可以灌输自定义行为。例如,

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;
于 2010-04-16T08:48:51.853 回答
0

更好的是使用 boost minmax 元素:

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;
于 2010-04-17T21:23:26.687 回答