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