티스토리 뷰
1. 비교 함수 사용
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point {
int x, y;
};
bool cmp(const Point& u, const Point& v) {
if (u.x < v.x)
return true;
else if (u.x == v.x)
return u.y < v.y;
else
return false;
}
int main() {
int n;
cin >> n;
vector<Point> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i].x;
cin >> a[i].y;
}
sort(a.begin(), a.end(), cmp);
for (int i = 0; i < n; i++) {
cout << a[i].x << " " << a[i].y << '\n';
}
return 0;
}
2. 연산자 오버로딩 사용
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Point {
int x, y;
bool operator <(const Point& v) const {
if (x < v.x)
return true;
else if (x == v.x)
return y < v.y;
else
return false;
}
};
int main(void) {
int n;
cin >> n;
vector<Point> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i].x;
cin >> a[i].y;
}
sort(a.begin(), a.end());
for (int i = 0; i < n; i++) {
cout << a[i].x << " " << a[i].y << '\n';
}
return 0;
}
'백준 알고리즘 기초 강좌' 카테고리의 다른 글
5장 정렬 - (5) Stable Sorting (0) | 2017.10.10 |
---|---|
5장 정렬 - (4) 11651번 좌표 정렬하기2 (0) | 2017.10.10 |
5장 정렬 - (2) 11650번 좌표 정렬하기 (0) | 2017.10.10 |
5장 정렬 - (1) 정렬 (0) | 2017.10.06 |
4장 수학 - (8) 소인수분해, 팩토리얼, 조합 (0) | 2017.10.06 |