Re: stl map key
 
andre <as@yahoo.com> wrote:
Hi,
anybody can advise how to get a key from the map having value only?
The other way around its easy of course, and map is supposed to be used like
that.
But I need to find a key for a given value.
thanks
  I am aware that this doesn't exactly answer your question,
  but in case you find yourself doing this repeatedly and if
  you're sure that there's always a one-to-one relationship
  between keys and values, you might want to create a reversed
  map where keys and values are swapped.
  I have this in my toolbox:
    // Caution! I had to copy-paste this together from several
    //          functions, so it might contain silly errors
    template< typename T1, typename T2 >
    inline void build_reverse_map(const std::map<T1,T2>& map, std::map<T2,T1>& reverse_map)
    {
      typedef std::map<T1,T2>                         map_type;
      typedef std::map<T2,T1>                         reverse_map_type;
      typedef typename reverse_map_type::value_type   reverse_value_type;
      for( typename map_type::const_iterator it=map.begin(),
                                            end=map.end(); it!=end; ++it ) {
        assert( reverse_map.insert(reverse_value_type(it->second,it->first)).second );
      }
    }
  Use it like this:
    void f()
    {
      std::map<int,string> my_map;
      // fill 'my_map'
      std::map<string,int> my_reverse_map;
      build_reverse_map(my_map,my_reverse_map);
      // use reverse map
    }
  HTH,
  Schobi
-- 
SpamTrap@gmx.de is never read
I'm Schobi at suespammers dot org
"The sarcasm is mightier than the sword."
Eric Jarvis