June 17th, 2013, 05:19 PM
Finding maximum value in map
I need to find the maximum value of a map.
this is how I did it:
I want to do it using only STL functions/methods.
using namespace std;
bool compare(pair<int, double> a, pair<int, double> b)
map<int, double> aMap;
pair<int, double> p=*max_element(aMap.begin(), aMap.end(), compare);
cout<<"Maximum value is:"<<p.second;
is there a way to do it?
June 17th, 2013, 07:31 PM
What's wrong with your current method?
June 18th, 2013, 01:42 AM
It just that the assignment requires to only use STL functions to find the maximum value in the map.
June 18th, 2013, 02:18 AM
Hint: map already arranges its data in sorted order. You just need to tell it how you expect it to order your data (note that the template can take an optional parameter that tells it how to sort your object).
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
June 18th, 2013, 03:09 AM
That's true but only for key value, not mapped value. In the given code maximum mapped value is evaluated.
Originally Posted by Scorpions4ever
so.very.tired, use an iterator:
Create a loop which increments your map's iterator from begin() to end(). Inside the loop check if mapped value of iterator it->second is greater than maximum value yet found.
map<int, double>::iterator it;
June 18th, 2013, 07:39 AM
You're already using the STL for everything except cout, so what's wrong with your current method?
That is being taken care by the max_element call.