Sorting a std::map by value before output & destroy

后端 未结 5 842
天涯浪人
天涯浪人 2020-12-01 11:30

I\'m aware that map is not prepared to be sorted. It\'s heavily optimized for fast and random key access and actually doesn\'t support std::sort.

My cur

5条回答
  •  渐次进展
    2020-12-01 12:07

    Another possibility is to build a reverse map. For you that would be std::map. Entries in the reverse map are sorted by their value.

    The following is what I have in my tool box for such occasions:

    template< typename TK, typename TV, class TP, class TA, typename T1, typename T2 >
    inline void asserted_insert(std::map& m, const T1& k, const T2& v)
    {
      typedef std::map                   map_type;
      typedef typename map_type::value_type           value_type;
      assert( m.insert(value_type(k,v)).second );
    }
    
    template< class TMap > struct reverse_map;
    template< typename T1, typename T2 > struct reverse_map< std::map > {
      typedef std::map                         result_t;
    };
    
    template< typename T1, typename T2, class TP1, class TA1, class TP2, class TA2 >
    inline void build_reverse_map(const std::map& map, std::map& reverse_map)
    {
      typedef std::map                 map_type;
    
      for( typename map_type::const_iterator it=map.begin(),
                                            end=map.end(); it!=end; ++it ) {
        asserted_insert( reverse_map, it->second, it->first );
      }
    }
    

    This code assumes that values are unique, too (and throws an assertion, if this is not the case). If this doesn't apply to your problem, you could easily change the code to use a multi map.

提交回复
热议问题