Map을 value 기준으로 정렬하기
→ 정확히는 map 을 정렬하는 것이 아니고, map의 요소들을 value 기준으로 정렬한다.
1.
map 을 vector 로 이동
2.
vector 를 second 기준으로 정렬
map을 vector로 이동
map의 key, value가 <int, int> 일때
vector<pair<int, int>> v(m.begin(), m.end());
C++
복사
value 기준 비교 함수 작성
map의 key, value가 <int, int> 일때
bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
if (a.second == b.second) return a.first < b.first;
return a.second < b.second;
}
C++
복사
정렬
map의 key, value가 <int, int> 일때
sort(v.begin(), v.end(), cmp);
C++
복사
예제)
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#define pp pair<int,int>
using namespace std;
map<int, int> m;
bool cmp(const pp& a, const pp& b) {
if (a.second == b.second) return a.first < b.first;
return a.second < b.second;
}
void Map_Setting() {
for (int i = 0; i < 1; ++i) m[1]++;
for (int i = 0; i < 5; ++i) m[2]++;
for (int i = 0; i < 3; ++i) m[3]++;
}
int main() {
Map_Setting();
for (auto num : m) {
cout << "key: " << num.first << " | value: " << num.second << "\n";
}
cout << "\n=======sort========\n\n";
vector<pp> vec( m.begin(), m.end() );
sort(vec.begin(), vec.end(), cmp);
for (auto num : vec) {
cout << "key: "<< num.first << " | value: " << num.second << "\n";
}
return 0;
}
/* 출력
key: 1 | value: 1
key: 2 | value: 5
key: 3 | value: 3
=======sort========
key: 1 | value: 1
key: 3 | value: 3
key: 2 | value: 5
*/
C++
복사