Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) GetKeyWithMaxValue

 

GetKeyWithMaxValue is a std::map code snippet to obtain the key with the highest value.

 

#include <algorithm>
#include <cassert>
#include <map>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>

///Obtain the key that corresponds to the highest value
//From http://www.richelbilderbeek.nl/CppGetKeyWithMaxValue.htm
template <class Key, class Value>
const Key GetKeyWithMaxValue(const std::map<Key,Value>& v)
{
  assert(!v.empty());
  return std::max_element(
    v.begin(),v.end(),
    boost::lambda::bind(&std::pair<Key,Value>::second, boost::lambda::_2)
     > boost::lambda::bind(&std::pair<Key,Value>::second, boost::lambda::_1)
   )->first;
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict