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