How to check if a key exist in map in C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <map>
 
int main ()
{
    std::map<char, int> mp;
 
    mp['a'] = 1;
    mp['x'] = 7;
    mp['r'] = 9;
 
    if (mp.count('x') > 0)
      std::cout << "Found";
    else 
      std::cout << "Not Found";
    
    return 0;
}
 
 
 
/*
run:
 
Found
 
*/

 



answered Apr 13, 2020 by avibootz
edited Apr 13, 2020 by avibootz
0 votes
#include <iostream>
#include <string>
#include <map>
 
int main ()
{
    std::map<char, int> mp;
 
    mp['a'] = 1;
    mp['x'] = 7;
    mp['r'] = 9;
 
    std::map<char, int>::iterator it = mp.find('x');

    if (it == mp.end())
      std::cout << "Not Found";
    else 
      std::cout << "Found";
    
    return 0;
}
 
 
 
/*
run:
 
Found
 
*/

 



answered Apr 13, 2020 by avibootz

Related questions

4 answers 653 views
1 answer 253 views
1 answer 231 views
1 answer 173 views
1 answer 183 views
2 answers 294 views
...