#1 Sort함수 정렬 조건 custom하기 (구조체 정렬하기)
변환 함수를 만들고 sort함수의 세번째 인자로 넣어주기.
//오름차순
int cmp_by_category(pair<string, int>&x, pair<string, int>&y) {
return x.second < y.second;
}
//내림차순
int cmp_by_views(info x, info y) {
return x.views > y.views;
}
sort(vec.begin(), vec.end(), cmp_by_category);
#2 map to vector
map을 생성할 때 key-value로 이어지는 자료형을 pair<>로 바꾸면서
map.begin() 과 map.end()를 통해서 바꿔준다
예시
unordered_map<string, int> rank_map;
// map에 데이터 추가 생략
//변환
vector<pair<string, int>> map2vec(rank_map.begin(), rank_map.end());
//정렬 #1번에서 설명한 것처럼 key와 value중 무엇을 기준으로 정렬할 것인지 함수 주기.
sort(map2vec.begin(), map2vec.end(), cmp1);
'알고리즘 문제풀이' 카테고리의 다른 글
JS로 알고리즘 (0) | 2024.02.02 |
---|---|
프로그래머스 [주식가격] 문제 스택으로 풀기 (0) | 2024.01.19 |
Hash를 위한 unoredered_map과 map (+JS구현) (0) | 2024.01.15 |
모듈러 연산 정리와 이항계수 문제 풀이 (0) | 2024.01.12 |
우선순위 큐 (Heap) 구현하기 (0) | 2024.01.08 |