Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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 129 views
129 views asked Apr 8, 2020 by avibootz
2 answers 262 views
3 answers 136 views
3 answers 145 views
1 answer 168 views
1 answer 172 views
1 answer 162 views
...