Ordering a map by value

So I have a map of the form:
std::map<std::string, int> m;

I want to order this by its int value, but I don't know how to write such a function. I've had two attempts thus far:

One by using std::pair, as a map consists of pairs.
1
2
3
bool cmp(std::pair<std::string, int> p1, std::pair<std::string, int> p2) {
  return p1.second < p2.second;
}



The other by trying to use maps, which seemed off to me at first, but I still tried it out (obviously it didn't work):
1
2
3
bool cmp(std::map<std::string, int> m1, std::map<std::string, int> m2) {
  return m1.begin()->second < m2.begin()->second;
}



How do I write a function that compares the values of a map such that I can use it to sort the map?
1
2
3
4
5
6
7
8
std::vector< std::pair< int, std::string > > sorted_on_values( const std::map< std::string, int >& map )
{
    std::vector< std::pair< int, std::string > > result ;
    for( const auto& pair : map ) result.emplace_back( pair.second, pair.first ) ; // *** note: second,first

    std::sort( std::begin(result), std::end(result) ) ;
    return result ;
}

http://coliru.stacked-crooked.com/a/ccfa3e601b5d2589

Note: If the map is large, wrap references to the strings in std::reference_wrapper<> to avoid making copies.
http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
You could use boost::multi_index.
Topic archived. No new replies allowed.