How to initialize map with for loop in C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <map>

void printMap(std::map<int, int> mp) {
  for (auto &s: mp) {
        std::cout << s.first << ": " << s.second << '\n';
  }    
}
  
int main ()
{
    std::map<int, int> mp;
    
    for (int i = 0; i < 10; i++) 
        mp[i] = 0;

    printMap(mp);

    return 0;
}
  
  
  
/*
run:
  
0: 0
1: 0
2: 0
3: 0
4: 0
5: 0
6: 0
7: 0
8: 0
9: 0
  
*/

 



answered Apr 13, 2020 by avibootz
0 votes
#include <iostream>
#include <string>
#include <map>

void printMap(std::map<int, char> mp) {
  for (auto &s: mp) {
        std::cout << s.first << ": " << s.second << '\n';
  }    
}
  
int main ()
{
    std::map<int, char> mp;
    
    for (int i = 0; i < 10; i++) 
        mp[i] = 97 + i;

    printMap(mp);

    return 0;
}
  
  
  
/*
run:
  
0: a
1: b
2: c
3: d
4: e
5: f
6: g
7: h
8: i
9: j
  
*/

 



answered Apr 13, 2020 by avibootz

Related questions

3 answers 242 views
1 answer 163 views
1 answer 204 views
1 answer 165 views
1 answer 237 views
2 answers 158 views
158 views asked Apr 14, 2020 by avibootz
...