Source:
#include <iostream>
#include <cstdlib>
#include <map>
#include <list>
#include <iterator>
typedef int Key;
typedef std::string Value;
typedef std::multimap<Key,Value> Map;
typedef std::list<Value> List;
std::ostream& operator<<( std::ostream& o, const Map& map )
{
for ( Map::const_iterator it = map.begin(); it != map.end(); ++it )
o << "map[" << it->first << "] = \"" << it->second << "\"" << std::endl;
return o;
}
std::ostream& operator<<( std::ostream& o, const List& list )
{
o << "list = { ";
for ( List::const_iterator it=list.begin(); it!=list.end(); ++it )
{
if ( it!=list.begin() )
o << ", ";
o << "\"" << *it << "\"";
}
o << " }" << std::endl;
return o;
}
struct get_second : std::unary_function<Map::value_type, Value>
{
result_type operator()( argument_type i )
{
return i.second;
}
};
List find_double_keys( const Map& map )
{
List result;
// Empty map, nothing to do
if ( map.empty() )
return result;
Map::const_iterator it = map.begin();
while ( it != map.end() )
{
// Find range of equal values [it;last[
Map::const_iterator last = ++Map::const_iterator(it);
while ( last->first == it->first && last != map.end() )
++last;
// Check the range is more than 1 element
if ( last != ++Map::const_iterator(it) )
{
std::transform( it, last, std::back_inserter(result), get_second() );
}
// Terminate or continue
if ( last != map.end() )
it = ++last;
else
return result;
}
return result;
}
int main( int, char** )
{
Map map;
List list;
map.insert( std::make_pair<Key,Value>(0,"a") );
map.insert( std::make_pair<Key,Value>(1,"b") );
map.insert( std::make_pair<Key,Value>(0,"c") );
map.insert( std::make_pair<Key,Value>(0,"d") );
map.insert( std::make_pair<Key,Value>(2,"j") );
map.insert( std::make_pair<Key,Value>(2,"k") );
std::cout << "map:" << std::endl << map;
list = find_double_keys(map);
std::cout << std::endl << "list:" << std::endl << list;
return EXIT_SUCCESS;
}
Output:
~/Projects > g++ test.cpp -o test && ./test
map:
map[0] = "a"
map[0] = "c"
map[0] = "d"
map[1] = "b"
map[2] = "j"
map[2] = "k"
list:
list = { "a", "c", "d", "j", "k" }