"Kevin W." <co*****@in.sig> wrote:
How do I sort a map by the value, rather than the key? (either
automatically or with the sort function.)
First start with a test:
int main() {
map< char, int > current;
current['a'] = 5;
current['b'] = 4;
current['c'] = 3;
map< int, char > other = converse_map( current );
map< int, char >::iterator begin( other.begin() );
assert( begin->first == 3 );
assert( begin->second == 'c' );
++begin;
assert( begin->first == 4 );
assert( begin->second == 'b' );
++begin;
assert( begin->first == 5 );
assert( begin->second == 'a' );
cout << "OK";
}
When the above prints "OK" you know you are done. Now write the
'converse_map' function...
map< int, char > converse_map( const map< char, int >& o )
{
map< int, char > result;
for ( map< char, int >::const_iterator begin( o.begin() );
begin != o.end(); ++begin )
result.insert( make_pair( begin->second, begin->first ) );
return result;
}
Then turn it into a template...
template < typename T, typename U >
map< U, T > converse_map( const map< T, U >& o )
{
map< U, T > result;
for ( typename map< T, U >::const_iterator begin( o.begin() );
begin != o.end(); ++begin )
result.insert( make_pair( begin->second, begin->first ) );
return result;
}