좌표 정렬하기 1과 다르게 이번엔 y좌표를 먼저 보고 x좌표를 본다. 비교함수만 다르게 넣어주면 간단하게 해결할 수  있다.

 

1. 비교 함수 정의

#include <bits/stdc++.h>

using namespace std;

struct Pos {
	int x;
	int y;
};

bool compare(const Pos& p1, const Pos& p2){
    if(p1.y == p2.y) return p1.x < p2.x;
    return p1.y < p2.y;
}

Pos pos[100001];

int main() {
	ios::ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int n;
	cin >> n;

	for (int i = 0; i < n; ++i) cin >> pos[i].x >> pos[i].y;

	sort(pos, pos + n, compare);

	for (int i = 0; i < n; ++i) cout << pos[i].x << ' ' <<  pos[i].y << '\n';

	return 0;
}

2. operator< 정의

#include <bits/stdc++.h>

using namespace std;

struct Pos {
	int x;
	int y;

	bool operator< (Pos& p) {
		if (this->y == p.y) return this->x < p.x;
		return this->y < p.y;
	}
};

Pos pos[100001];

int main() {
	ios::ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int n;
	cin >> n;

	for (int i = 0; i < n; ++i) cin >> pos[i].x >> pos[i].y;

	sort(pos, pos + n);

	for (int i = 0; i < n; ++i) cout << pos[i].x << ' ' <<  pos[i].y << '\n';

	return 0;
}

3. Pair 클래스

#include <bits/stdc++.h>

using namespace std;

bool compare(const pair<int, int>& p1, const pair<int, int>& p2) {
	if (p1.second == p2.second) return p1.first < p2.first;
	return p1.second < p2.second;
}

pair<int, int> pos[100001];

int main() {
	ios::ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	
	int n;
	cin >> n;

	for (int i = 0; i < n; ++i) cin >> pos[i].first >> pos[i].second;
    
	sort(pos, pos + n, compare);
    
	for (int i = 0; i < n; ++i) cout << pos[i].first << ' ' << pos[i].second << '\n';

	return 0;
}

+ Recent posts