devLupin / algorithm

PS
1 stars 0 forks source link

C++ STL <map> #14

Open devLupin opened 1 year ago

devLupin commented 1 year ago
devLupin commented 1 year ago

mapkey, 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;
}