Open devLupin opened 1 year ago
map
의 key
, value
를 기준으로 정렬하고 싶다면,
vector
에 값을 다시 할당한 후 벡터를 정렬해야 한다.
왜냐면, 맵의 key는 index 자체이므로, 이걸 이용한 정렬을 할 수가 없다. (당연한 사실...)
이것에 대한 영감은 백준 온라인 저지의 문제이다.
#include<bits/stdc++.h>
#include <unordered_map>
using namespace std;
using psi = pair<string, int>;
bool compare(const psi &a, const psi &b) {
if (a.second == b.second) {
if (a.first.size() == b.first.size()) return a.first < b.first;
return a.first.size() > b.first.size();
}
return a.second > b.second;
}
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
unordered_map<string, int> um;
// map에 값이 채워졌다.
vector<psi> tmp(um.begin(), um.end());
sort(tmp.begin(), tmp.end(), compare);
for (psi a : tmp) cout << a.first << '\n';
return 0;
}
map
vsunordered_map
map
은 red-black tree 기반으로 키의 순서 유지unordered_map
은 해시 테이블을 사용해 키의 순서 유지X