알고리즘
pair 구성요소를 같은 vector 정렬하기
kyeongjun-dev
2020. 8. 14. 16:36
sort 활용
- 예시
vector<pair<int,int>> v;
v.sort(v.begin(), v.end());
위처럼 하면 자동으로 first를 기준으로 오름차순으로 정렬된다
first가 같으면 second를 기준으로 오름차순으로 정렬된다.
second를 기준으로 우선 오름차순 정렬 후, second가 같으면 x를 기준으로 오름차순 정렬
- 코드1 (백준 11651)
#include <bits/stdc++.h>
using namespace std;
bool compare(pair<int, int> a, pair<int, int>b){
if(a.second==b.second){
return a.first<b.first;
}else{
return a.second<b.second;
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
//y 좌표가 증가하는 순으로. y좌표가 같으면 x좌표가 증가하는 순으로
int c;
cin>>c;
vector<pair<int,int>> v(c);
for(int i=0; i<c; i++){
cin>>v[i].first>>v[i].second;
}
sort(v.begin(), v.end(), compare);
for(int i=0; i<c; i++){
cout << v[i].first << ' ' << v[i].second << '\n';
}
return 0;
}
compare 함수의 인자로 뭐가 들어가야 하는지 자주 햇갈리는데, 인자로
정렬하려는 자료형의 인자(여기서는 pair<int,int>)를 넣어주면 된다.
- 코드2 (백준 10814)
#include <bits/stdc++.h>
using namespace std;
bool compare(pair<pair<int,string>,int> a, pair<pair<int,string>,int> b){
if(a.first.first!=b.first.first){
return a.first.first<b.first.first;
}else{
return a.second<b.second;
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int c;
cin>>c;
vector<pair<pair<int,string>,int>> v(c);
for(int i=0; i<c; i++){
cin>>v[i].first.first>>v[i].first.second;
v[i].second=i;
}
sort(v.begin(), v.end(), compare);
for(int i=0; i<c; i++){
cout<<v[i].first.first<<' '<<v[i].first.second << '\n';
}
return 0;
}