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
|
#include <iostream>
#include <string>
#include <map>
#include <set>
template < typename KEY, typename VALUE > // return bool (true if non-duplicate value was inserted)
bool did_insert( std::map< KEY, std::set<VALUE> >& map, const KEY& key, const VALUE& value )
{ return map[key].insert(value).second ; }
template < typename KEY, typename VALUE > // return iterator to map
typename std::map< KEY, std::set<VALUE> >::iterator
inserted_at( std::map< KEY, std::set<VALUE> >& map, const KEY& key, const VALUE& value )
{
typename std::map< KEY, std::set<VALUE> >::iterator map_iter = map.find(key) ;
if( map_iter == map.end() ) // key was not found, insert { key, empty set }
{
std::set<VALUE> empty_set ;
map_iter = map.insert( std::make_pair( key, empty_set ) ).first ;
}
map_iter->second.insert(value) ; // insert value into set
return map_iter ; // return iterator of map
}
int main()
{
typedef std::map< std::string, std::set<int> > map_type ;
map_type my_map ;
bool b = did_insert( my_map, std::string("abcd"), 23 ) ;
std::cout << std::boolalpha << b << '\n' ; // true
b = did_insert( my_map, std::string("efgh"), 23 ) ;
std::cout << std::boolalpha << b << '\n' ; // true
b = did_insert( my_map, std::string("abcd"), 23 ) ;
std::cout << std::boolalpha << b << '\n' ; // false (duplicate value was not inserted)
for( int i = 10 ; i < 15 ; ++i ) did_insert( my_map, std::string("abcd"), i ) ;
// -----------------------------------------------------------------------
const map_type::iterator map_iter = inserted_at( my_map, std::string("abcd"), 19 ) ;
std::cout << map_iter->first << ' ' ; // abcd (key)
std::set<int>& set = map_iter->second ;
for( std::set<int>::iterator set_iter = set.begin() ; set_iter != set.end() ; ++set_iter )
std::cout << *set_iter << ' ' ; // 10 11 12 13 14 19 23 (values)
std::cout << '\n' ;
}
|