How to find the max value in unordered_map with C++

2 Answers

0 votes
#include <iostream>
#include <unordered_map>
#include <vector>

int main()
{
    std::vector<int> vec = { 2, 5, 3, 3, 5, 9, 1, 5, 7, 5, 5, 3 };
    std::unordered_map<int, int> umap;
   
    int len = vec.size();
   
    for (int i = 0; i < len; i++) {
        umap[vec[i]]++;
    }
     
    int max = 0;
    for (auto pair: umap) {
        std::cout << pair.first << " " << pair.second << std::endl;
        if (pair.first > max) {
            max = pair.first;
        }
    }
   
    std::cout << "max : " << max << std::endl;
}
   
   
/*
run:
   
7 1
1 1
9 1
3 3
5 5
2 1
max : 9
   
*/

 



answered Feb 20, 2019 by avibootz
edited Sep 14, 2024 by avibootz
0 votes
#include <unordered_map>
#include <iostream>
#include <string>

int main() {
    std::unordered_map<std::string, int> umap = {
        {"c++", 11},
        {"c", 17},
        {"c#", 20},
        {"java", 19}
    };

    std::string maxKey;
    int max = -1;
    for (const auto& pair : umap) {
        if (pair.second > max) {
            max = pair.second;
        }
    }

    std::cout << "Max value = " << max << std::endl;
}

   
   
/*
run:
   
Max value = 20
   
*/

 



answered Sep 14, 2024 by avibootz

Related questions

1 answer 141 views
2 answers 165 views
1 answer 132 views
132 views asked Sep 17, 2022 by avibootz
3 answers 296 views
296 views asked Feb 20, 2019 by avibootz
1 answer 175 views
3 answers 343 views
...