fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4.  
  5. bool insert( const std::string &key , const int value , std::map<std::string , int> &m );
  6.  
  7. int main()
  8. {
  9. // your code goes here
  10. std::map<std::string,int> m;
  11. m["apple"] = 1;
  12. m["grape"] = 2;
  13.  
  14. insert( "orange" , 1 , m );
  15.  
  16. insert( "apple" , 3 , m );
  17.  
  18. insert( "orange" , 3 , m );
  19.  
  20. for( const auto &it : m )
  21. std::cout << it.first << " = " << it.second << std::endl;
  22. return 0;
  23. }
  24.  
  25. bool insert( const std::string &key , const int value , std::map<std::string , int> &m )
  26. {
  27. bool found = false;
  28. if( m.find(key) != m.end() )
  29. {
  30. found = true;
  31. }
  32. else
  33. {
  34. for( const auto &it : m ) //for( std::map<std::string,int>::iterator it = m.begin() , it != m.end(); ++it )
  35. {
  36. if( it.second == value )
  37. {
  38. found = true;
  39. }
  40. }
  41. }
  42.  
  43. if( !found )
  44. {
  45. m[key] = value;
  46. std::cout << "The item was added" << std::endl;
  47. }
  48. else
  49. {
  50. std::cout << "The item was not added" << std::endl;
  51. }
  52.  
  53. return( found );
  54. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
The item was not added
The item was not added
The item was added
apple = 1
grape = 2
orange = 3