Map 정렬
Key 기준 정렬
map은 기본적으로 key값을 기준으로 오름차순 정렬을 수행한다.
int main() {
map<int, int> m;
m.insert({ 1, 5 });
m.insert({ 3, 1 });
m.insert({ 2, 10 });
for (auto v : m) {
cout << v.first << " : " << v.second << endl;
}
return 0;
}
이는 map의 기본 템플릿에서 Compare 인자로 less<>를 사용하기 떄문에 만약 key값을 기준으로 내림차순 정렬을 하고 싶은경우 Compare인자로 greater<key>를 넣어주면 된다.
int main() {
map<int, int, greater<int>> m; // compare 인자로 greater<key> 넘겨줌
m.insert({ 1, 5 });
m.insert({ 3, 1 });
m.insert({ 2, 10 });
for (auto v : m) {
cout << v.first << " : " << v.second << endl;
}
return 0;
}
Value 기준 정렬
map 자체로는 별도의 sort함수가 존재하지 않는다.
따라서 map을 먼저 vector로 변환하고 정렬을 수행해야한다.
// second (value) 기준 오름차순 정렬
bool static compare(pair<int,int> &a , pair<int,int> &b) {
return a.second < b.second;
}
int main() {
map<int, int, greater<int>> m;
m.insert({ 1, 5 });
m.insert({ 3, 1 });
m.insert({ 2, 10 });
// map -> vector 변환
vector<pair<int, int>> vec(m.begin(), m.end());
// 커스텀한 compare 함수 기반으로 정렬
sort(vec.begin(), vec.end(), compare);
for (auto v : vec) {
cout << v.first << " : " << v.second << endl;
}
return 0;
}
value값을 기준으로 성공적으로 오름차순 정렬이 된 것을 확인할 수 있다.
compare 함수를 커스텀하면 더 다양한 정렬을 수행할 수 있는데 자세한내용 >> https://qoridhc.tistory.com/24 참조
'백준 > 팁' 카테고리의 다른 글
sort 정렬 순서 커스텀하기 (feat. 백준 8979) (0) | 2023.08.08 |
---|