SMALL
안녕하세요 오늘은 이중 pair vector를 이용하여 정렬 문제를 풀어보겠습니다.
코드:
#include <bits/stdc++.h>
#include <vector>
using namespace std;
bool cp(pair<string, pair<int, int> > a ,
pair<string, pair<int, int> > b){
if(a.second.first == b.second.first){
return a.second.second< b.second.second;
}
return a.second.first< b.second.first;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int N;
cin>>N;
vector<pair<string, pair<int, int> > > v;
for(int i = 0; i<N; i++){
int x;
int ind = i;
string y;
cin>>x>>y;
v.emplace_back(pair<string, pair<int, int> >(y, pair<int, int>(x, ind)));
}
sort(v.begin(), v.end(), cp);
for(int i = 0; i<N; i++){
cout<<v[i].second.first<<" "<<v[i].first<<"\n";
}
}
string, int, int를 pair로 가지는 vector를 선언 하는 방법은
vector<pair<string, pair<int, int> > > v; 입니다. 이렇게 되면 {string, int, int}가 pair가 됩니다.
대입은,
v.emplace_back(pair<string, pair<int, int>>(y, pair<int, int>(x, ind))); 이렇게 하면 됩니다.
index의 줄인말인 ind를 int형으로 변수 선언을 해주어서, 각 pair가 몇번째로 입력 받았는지 저장하기 위해서
int ind = i;
를 해줍니다.
sort할때, cp라는 조건을 만들어서 그에 따른 정렬을 해줍니다.
if(a.second.first == b.second.first){
return a.second.second< b.second.second;
return a.second.first< b.second.first;
여기서, 두 경우의 나이가 같을때 ind값이 더 작은것을 앞으로 정렬시켜주고, 그러지 않으면 나이 작은 순서대로 앞으로 보내줍니다.
LIST
'BOJ 문제풀이' 카테고리의 다른 글
백준 2475번 c++ 풀이 (0) | 2021.08.04 |
---|---|
백준 2108번 c++ 풀이 (1) | 2021.08.04 |
백준 1181번 c++ 풀이 (0) | 2021.08.03 |
백준 11651번 c++ 풀이 (0) | 2021.08.03 |
백준 11650 c++ 풀이 (0) | 2021.08.02 |