我如何使用std :: sort按x坐标对结构进行排序

时间:2013-02-27 00:13:56

标签: c++ oop

这是我的结构:

class Pont{

private:

    int x, y;
public:

    Pont( int x=0, int y=0);
    int getX() const;
    int getY() const;
    void setX( int x );
    void setY( int y );
    void move( int nx, int ny);
};

我填写了我的Pont类型pontok:

while(n < N){

        int x=(rand()%2000);
        int y=(rand()%2000);
        Pont p(x,y);
        if(!letezike(p,n)){
            pontok[n]=p;
            ++n;
        }

我已尝试过这个:

bool sorter(Pont const& lhs, Pont const& rhs) {

   if (lhs.getX() != rhs.getX())
        return lhs.getX() < rhs.getX();
}

std::sort(pontok[0], pontok[N], &sorter);

2 个答案:

答案 0 :(得分:3)

删除!=支票。如果x值相等,它会为您的程序提供未定义的行为,因为该函数不会达到return语句。

bool sorter(Pont const& lhs, Pont const& rhs) {
    return lhs.getX() < rhs.getX();
}

如果x值相等,则会返回false,就像它应该做的那样。

此外,您对std::sort的来电不正确。假设pontok是一个大小为N的点数组,您需要执行以下操作:

std::sort(pontok, pontok + N, &sorter);

std::sort采用迭代器范围,该范围指向要排序的序列的开头和结尾。你传递了数组的两个元素。

答案 1 :(得分:1)

当X坐标相等时,你的sorter函数似乎没有返回任何内容,这是你的意思吗?!

可能很简单:

bool sorter(Pont const& lhs, Pont const& rhs) {
   return lhs.getX() < rhs.getX();
}