How to use map in C++

4 Answers

0 votes
#include <iostream>
#include <string>
#include <map>
 
void printMap(std::map<std::string, int> mp) {
  for (auto &s: mp) {
        std::cout << s.first << ": " << s.second << '\n';
  }    
}
 
int main ()
{
    std::map<std::string,int> mp = {
                    { "c++", 23 },
                    { "c", 6 },
                    { "python", 87 },
                    { "java", 980 } };
 
    printMap(mp);
 
    return 0;
}
 
 
 
/*
run:
 
c: 6
c++: 23
java: 980
python: 87
 
*/

 



answered Apr 13, 2020 by avibootz
edited Apr 13, 2020 by avibootz
0 votes
#include <iostream>
#include <string>
#include <map>
 
void printMap(std::map<std::string, int> mp) {
  for (auto &s: mp) {
        std::cout << s.first << ": " << s.second << '\n';
  }    
}
 
int main ()
{
    std::map<std::string,int> mp = {
                    { "c++", 23 },
                    { "c", 6 },
                    { "python", 87 },
                    { "java", 980 } };
 
    mp.at("c++") = 1000;
    mp.at("java") = 2000;
 
    printMap(mp);
 
    return 0;
}
 
 
 
/*
run:
 
c: 6
c++: 1000
java: 2000
python: 87
 
*/

 



answered Apr 13, 2020 by avibootz
edited Apr 13, 2020 by avibootz
0 votes
#include <iostream>
#include <string>
#include <map>
 
void printMap(std::map<char, int> mp) {
  for (auto &s: mp) {
        std::cout << s.first << ": " << s.second << '\n';
  }    
}
 
int main ()
{
    std::map<char, int> mp;
 
    mp['a'] = 1;
    mp['x'] = 7;
    mp['r'] = 9;
 
    printMap(mp);
 
    return 0;
}
 
 
 
/*
run:
 
a: 1
r: 9
x: 7
 
*/

 



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

void printMap(std::map<char, int> mp) {
   for (std::map<char,int>::iterator it = mp.begin(); it != mp.end(); it++)
        std::cout << it->first << ": " << it->second << '\n';
}

int main ()
{
    std::map<char, int> mp;

    mp['a'] = 1;
    mp['x'] = 7;
    mp['r'] = 9;

    printMap(mp);

    return 0;
}



/*
run:

a: 1
r: 9
x: 7

*/

 



answered Apr 13, 2020 by avibootz
...