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
|
#include <iostream>
#include <string>
#include <set>
#include <map>
bool add_value( std::map< std::string, std::set<int> >& map,
const std::string& key, int value )
{
return map[key].insert(value).second ;
}
int main()
{
std::map< std::string, std::set<int> > map ;
const auto try_add = [&] ( const std::string& key, int value )
{
std::cout << "key '" << key << "' value " << value << " : " ;
if( add_value( map, key, value ) ) std::cout << "inserted value\n" ;
else std::cout << "value is already present for this key\n" ;
};
try_add( "abcd", 7 ) ; // key 'abcd' value 7 : inserted value
try_add( "abcd", 8 ) ; // key 'abcd' value 8 : inserted value
try_add( "efgh", 7 ) ; // key 'efgh' value 7 : inserted value
try_add( "abcd", 7 ) ; // key 'abcd' value 7 : value is already present for this key
try_add( "abcd", 9 ) ; // key 'abcd' value 9 : inserted value
try_add( "efgh", 3 ) ; // key 'efgh' value 3 : inserted value
std::cout << "\nthe map contains:\n--------------\n" ;
for( const auto& [key,set] : map )
{
std::cout << "key '" << key << "' values: [" ;
for( int value : set ) std::cout << value << ' ' ;
std::cout << "]\n" ;
}
/*
the map contains:
--------------
key 'abcd' values: [7 8 9 ]
key 'efgh' values: [3 7 ]
*/
}
|