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

#문제

백준 10814번 나이순 정렬

#풀이

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

bool cmp(const pair<int, string>& x, const pair<int, string>& y)
{
	return x.first < y.first;
}

int main()
{
	ios::sync_with_stdio(false); cin.tie(NULL);

	int N;
	cin >> N;

	vector<pair<int, string>> list;

	for (int i = 0; i < N; ++i)
	{
		int age;
		string name;
		cin >> age >> name;

		list.push_back(make_pair(age, name));
	}

	stable_sort(list.begin(), list.end(), cmp);

	for (const auto& p : list)
	{
		cout << p.first << ' ' << p.second << '\n';
	}

	return 0;
}

#정리

입력받은 나이와 이름을 Algorithm 라이브러리의 sort 함수와 정렬 방법으로 사용자 정의 함수를 사용하여 1차 시도를 진행했다. 사용자 정의 함수인 cmp 함수에서는 이름은 비교하지 않고, 나이만 비교 후 return 하도록 코드를 작성하였다. 예제 출력은 맞췄지만, 채점에서 막혀서 알아보니 sort는 비안정적인 정렬 방법으로 원소들의 초기 순서를 보존하지 않는다고 한다. 그에 반해 stable_sort는 안정적인 정렬 방법으로 상대적인 정렬 순서가 유지된다고 한다. sort를 stable_sort로 바꿔서 채점하니 정답이 나왔다.




    Enjoy Reading This Article?

    Here are some more articles you might like to read next:

  • [백준] 10825번 국영수 / C++
  • [백준] 1764번 듣보잡 / C++
  • [백준] 1181번 단어 정렬 / C++
  • [백준] 11651번 좌표 정렬하기 2 / C++
  • [백준] 11650번 좌표 정렬하기 / C++