Click to See Complete Forum and Search --> : std::map max/min


gareth19
December 3rd, 2004, 10:31 AM
Is there a call to get these values?
Thx.

Philip Nicoletti
December 3rd, 2004, 11:01 AM
Could you explain what you want in a little more detail ?

begin() returns an iterator for the first element (which would be the
"min" for the key) . end() points to last element , so subtracting 1
points to last element.


#include <iostream>
#include <map>

using namespace std;

typedef std::map<int,int> MAP;
typedef std::pair<int,int> PAIR;

int main()
{

MAP squares_map;

squares_map.insert( PAIR(2,4) );
squares_map.insert( PAIR(0,0) );
squares_map.insert( PAIR(1,1) );
squares_map.insert( PAIR(6,36) );
squares_map.insert( PAIR(3,9) );

if (!squares_map.empty())
{
MAP::iterator it_min = squares_map.begin();

MAP::iterator it_max = squares_map.end(); // points to just past last element
--it_max; // points to last element

cout << "min element : " << it_min->first << " " << it_min->second << "\n";
cout << "max element : " << it_max->first << " " << it_max->second << "\n";
}

return 0;
}

gareth19
December 3rd, 2004, 12:07 PM
Ok. Thx Philip, that is what I wanted.