알고리즘/BOJ

[C++] 백준 10814번 나이순 정렬

Jay, Lee 2021. 3. 11. 22:05

단순히 sort 만 쓰면 당연하게도 틀리는 문

이 문제때문에 처음으로 stable_sort 를 써보았다.

stable_sort가 정리되어있는 www.cplusplus.com/reference/algorithm/stable_sort/

 

stable_sort - C++ Reference

function template std::stable_sort template void stable_sort ( RandomAccessIterator first, RandomAccessIterator last ); template void stable_sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp ); Sort elements preserving

www.cplusplus.com

여기랑 여러 블로그를 참조했다.

stable_sort 를 통해서 vector pair의 second를 조절할 수 있다는 것.

다시한번 공부하고 넘어가자.

#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
using namespace std;

bool cmp(pair<int, string> u, pair<int, string> v) {
	return u.first < v.first;
}

int main() {

	int testCase;
	cin >> testCase;

	vector<pair<int, string>> v;

	int age;
	string name;

	for (int i = 0; i < testCase; i++) {
		cin >> age >> name;
		v.push_back(make_pair(age, name));
	}

	//sort(v.begin(), v.end());  이렇게 정렬시키면 내가 원하는대로 입력순 출력이 불가
	stable_sort(v.begin(), v.end(), cmp);

	for (int i = 0; i < testCase; i++) {
		cout << v[i].first << " " << v[i].second << "\n";
	}

	v.clear();
	
	return 0;
}