[백준 10814번 C++] 나이순 정렬
10814번: 나이순 정렬
온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을
www.acmicpc.net
vector pair 사용 방법
//선언 방법
vector<pair<int, string>> v;
//벡터 삽입 방식 - { }로 pair을 묶어서 삽입
v.push_back({3, "cat"});
v.push_back({5, "dog"});
//벡터 출력 방식 - first, second 를 사용
cout << v[0].first << ", " v[0].second << "\n";
cout << v[1].first << ", " v[1].second << "\n";
[백준] 10814 c++ 나이순 정렬 :: hELLO, eVERYONE ! (tistory.com)
[백준] 10814 c++ 나이순 정렬
https://www.acmicpc.net/problem/10814 10814번: 나이순 정렬 온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한
imoracle.tistory.com
벡터 pair일 때 정렬하기
compare 함수를 이용해줘야한다. 이 함수의 return 값은 bool로 해줘야 함!
bool cmp(pair<int, string> age, pair<int, string> name)
{
return age.first < name.first;
}
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(pair<int, string> age, pair<int, string> name)
{
return age.first < name.first;
}
int main()
{
int n, m;
string s;
vector<pair<int, string>> v;
cin >> n;
for(int i=0; i<n; i++){
cin >> m >> s;
v.push_back({m, s});
}
sort(v.begin(), v.end(), cmp);
for(int i=0; i<n; i++){
cout << v[i].first << " " <<v[i].second<<"\n";
}
return 0;
}
이렇게 작성해줬는 데 틀렸고, sort 문을 stable_sort로 바꿔주니 맞았다
stable_sort() 병합정렬
sort : 기존의 순서를 보장하지않음.
stable_sort : 기존의 순서를 보장함.
[백준] 10814 c++ 나이순 정렬 :: hELLO, eVERYONE ! (tistory.com)
[백준] 10814 c++ 나이순 정렬
https://www.acmicpc.net/problem/10814 10814번: 나이순 정렬 온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한
imoracle.tistory.com
그렇게 최종 코드는
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(pair<int, string> age, pair<int, string> name)
{
return age.first < name.first;
}
int main()
{
int n, m;
string s;
vector<pair<int, string>> v;
cin >> n;
for(int i=0; i<n; i++){
cin >> m >> s;
v.push_back({m, s});
}
stable_sort(v.begin(), v.end(), cmp);
for(int i=0; i<n; i++){
cout << v[i].first << " " <<v[i].second<<"\n";
}
return 0;
}