### Thread: Finding maximum value in map

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
132
Rep Power
5

#### Finding maximum value in map

Hi.
I need to find the maximum value of a map.
this is how I did it:
Code:
```#include<iostream>
#include<map>
#include<algorithm>
using namespace std;

bool compare(pair<int, double> a, pair<int, double> b)
{
return a.second<b.second;
}

int main()
{
map<int, double> aMap;

aMap[12]=3.44;
aMap[1]=7.94;
aMap[5]=2.43;
aMap[7]=9.11;
pair<int, double> p=*max_element(aMap.begin(), aMap.end(), compare);
cout<<"Maximum value is:"<<p.second;
}```
I want to do it using only STL functions/methods.
is there a way to do it?
2. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jan 2013
Posts
159
Rep Power
22
What's wrong with your current method?

Jim
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
132
Rep Power
5
Nothing.
It just that the assignment requires to only use STL functions to find the maximum value in the map.
4. 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).
5. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2009
Posts
45
Rep Power
11
Originally Posted by Scorpions4ever
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).
That's true but only for key value, not mapped value. In the given code maximum mapped value is evaluated.

so.very.tired, use an iterator:
Code:
`map<int, double>::iterator it;`
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.
6. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jan 2013
Posts
159
Rep Power
22
Nothing.
It just that the assignment requires to only use STL functions to find the maximum value in the map.
You're already using the STL for everything except cout, so what's wrong with your current method?

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.
That is being taken care by the max_element call.

Jim