简体   繁体   中英

how can i sort my struct by x coordinate using std::sort

here is my struct:

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);
};

and I fill my Pont type pontok :

while(n < N){

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

and I've tried with this:

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);

Remove that != check. It gives your program undefined behaviour if the x values are equal because the function will not reach a return statement.

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

If the x values are equal, this will return false , as it should do.

Also, your call to std::sort is incorrect. Assuming pontok is an array of points of size N , you need to do:

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

std::sort takes an iterator range which point to the beginning and end of the sequence you want to sort. You were passing in two elements of your array.

Your sorter function appears to return nothing when the X co-ordinates are equal, is that what you meant?!

It could be simply:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM