C++ 맵 최대값

Jmnote (토론 | 기여)님의 2024년 1월 12일 (금) 01:37 판 (→‎같이 보기)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

C++ 맵 최대값
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;

int main() {
    map<string,int> m = {{"apple",1},{"banana",5},{"cranberry",3}};
    string maxKey = "";
    int maxValue = 0;
    for(auto& it: m) {
        if(it.second > maxValue) {
            maxValue = it.second;
            maxKey = it.first;
        }
    }
    cout << maxKey << endl; // banana
    cout << maxValue << endl; // 5
}
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;

int main() {
    map<string,int> m = {{"apple",1},{"banana",5},{"cranberry",3}};
    using pair_type = decltype(m)::value_type;
    auto pr = max_element(begin(m), end(m), [](const pair_type& p1, const pair_type& p2) {
        return p1.second < p2.second;
    });
    cout << pr->first << endl; // banana
    cout << pr->second << endl; // 5
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}