1. 개요
key-value의 쌍으로 값을 저장하는 자료구조인 map이 있다. map은 기본적으로 key 값을 기준으로 정렬이 된다. 하지만 value 값으로 정렬을 하고자 할 때에는 어떻게 해야할까 ? 번거롭기는 하지만 map을 vector<pair<type, type>>으로 옮긴 후 second 값을 기준으로 sort를 해주면 된다.
2. 코드
#include <map>
#include <vector>
#include <algorithm>
int main()
{
map<int, int> m = {
{ 1, 3 },
{ 5, 4 },
{ 2, 1 }
};
vector<pair<int, int>> v(m.begin(), m.end());
sort(v.begin(), v.end(), [](const auto& a, const auto& b){
return a.second < b.second;
)};
for(auto& a : v)
{
cout << a.first << " " << a.second << endl; // 2 1, 1 3, 5 4
}
}
'코딩테스트 > 알고리듬' 카테고리의 다른 글
[코딩테스트] 자릿수 정렬 (0) | 2025.02.26 |
---|---|
[코딩테스트] 원형 연속부분수열 합 (0) | 2025.02.26 |
[코딩테스트] 피보나치 수 (0) | 2025.02.18 |
[코딩테스트] 10진수 ↔ 2진수 변환 (0) | 2025.02.17 |
[코딩테스트] 문자열 대소문자 변환 (0) | 2025.02.13 |