How to initialize an unordered_map in C++

3 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, 3, 3 };
    std::unordered_map<int, int> umap;
    
    int len = vec.size();
    
    for (int i = 0; i < len; i++) {
        umap[vec[i]]++;
    }
      
    for (auto pair: umap) {
        std::cout << pair.first << " " << pair.second << "\n";
    }
}

    
   
    
/*
run:
    
7 1
1 1
9 1
3 4
5 3
2 1
    
*/

 



answered Feb 20, 2019 by avibootz
edited Sep 17, 2022 by avibootz
0 votes
#include <iostream>
#include <unordered_map>
#include <vector>

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

    
   
    
/*
run:
    
7 14
1 2
9 18
3 6
5 10
2 4
    
*/

 



answered Feb 20, 2019 by avibootz
edited Sep 17, 2022 by avibootz
0 votes
#include <iostream>
#include <unordered_map>

int main()
{
    std::unordered_map<std::string, int> umap({ { "aaa", 1 },
                                                { "bbb", 2 },
                                                { "ccc", 3 },
                                                { "ddd", 4 }});
    
      
    for (auto pair: umap) {
        std::cout << pair.first << " " << pair.second << "\n";
    }
}

    
   
    
/*
run:
    
ddd 4
ccc 3
bbb 2
aaa 1
    
*/

 



answered Feb 20, 2019 by avibootz
edited Sep 17, 2022 by avibootz

Related questions

1 answer 175 views
1 answer 140 views
2 answers 164 views
1 answer 131 views
131 views asked Sep 17, 2022 by avibootz
2 answers 1,709 views
3 answers 343 views
...