How to insert new element into a map in C++

2 Answers

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;
    mp['w'] = 5;
  
    printMap(mp);
    
    mp.insert( std::pair<char, int>('c', 4)); 
    
    std::cout << '\n';
    printMap(mp);
     
    return 0;
}
  
  
  
/*
run:
  
a: 1
r: 9
w: 5
x: 7

a: 1
c: 4
r: 9
w: 5
x: 7
  
*/

 



answered 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;
    mp['w'] = 5;
  
    printMap(mp);
    
    mp.insert(std::pair<char, int>('c', 4)); 
    
    std::pair<std::map<char,int>::iterator,bool> it;
    it = mp.insert(std::pair<char, int>('r', 9883) );

    if (it.second == false) {
        std::cout << "Element 'r' already exist";
    }

    return 0;
}
  
  
  
/*
run:
  
a: 1
r: 9
w: 5
x: 7
Element 'r' already exist
  
*/

 



answered Apr 13, 2020 by avibootz

Related questions

1 answer 146 views
146 views asked Apr 8, 2020 by avibootz
2 answers 292 views
3 answers 162 views
3 answers 172 views
1 answer 182 views
1 answer 185 views
1 answer 175 views
...