Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ordering coordinates c++

I’m trying to order a list of coordinates in c++, but it’s not working.
i’m using c++ sort function, and first ordering the x values and then the y values

if n = 9 and the coordinates:

(2,2) (2,3) (1,2) (1,3) (2,1) (1,1) (3,2) (3,3) (3,1)

the output should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3 ,3)

But for some reason, it is:

(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,2)
(3,3)
(3,1)
#include <iostream>
#include <algorithm>
using namespace std;

typedef struct{
    short x;
    short y;
} coord;

bool comparex( coord a, coord b){
    if(a.x < b.x)
        return 1;
    else return 0;
}

bool comparey(coord a, coord b){
    
    if(a.x == b.x && a.y < b.y){
        return 1;
    } else return 0;
}


int main(){
    
    
    short n;
    coord v[1001];
    
    while(cin >> n){
        for (int i=1; i<=n; i++){
            cin >> v[i].x;
            cin >> v[i].y;
        }
        
        sort(v+1, v+n, comparex);
        sort(v+1, v+n, comparey);
        for (int i=1; i<=n; i++){
            cout << v[i].x << ' ' << v[i].y << endl;
        }
                    
    }

    
    return 0;
}

>Solution :

Your comparison is flawed:

bool comparey(coord a, coord b){
    
    if(a.x == b.x && a.y < b.y){
        return 1;
    } else return 0;
}

You always return 0 (should be false) when a.x != b.x. For example comparey({0,1}, {1,1}) == false but also comparey({1,1},{0,1}) == false.

You can use std::pair for the comparison:

bool comparey(coord a, coord b){
    return std::pair(a.x,a.y) < std::pair(b.x,b.y);
}

or use std::tie to avoid constructing the pairs:

bool comparey(coord a, coord b){
    return std::tie(a.x,a.y) < std::tie(b.x,b.y);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading