map::value_comp in C++.

  • From: "Graham Hardy" <graham.hardy@xxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Thu, 1 Nov 2007 22:46:38 -0700

Hi all - What I want to do is to take a std::map <std::string, int>, and to
sort it by the int value to be sent to a file in order from highest to
lowest. Now, I suspect it has something to do with the map::value_comp
function, but I don't quite understand how the following code actually
works. (This example was taken from a website, and doesn't reflect my goal
of map <string, int>.)

#include <iostream> 
#include <map> 

using namespace std;
 
int main ()
{
 map <char, int> mymap;
 map <char, int> :: iterator it;
 pair <char, int> highest; // I assume this 'pair' is an element of the map.
 
 mymap ['x'] = 1001;
 mymap ['y'] = 2002;
 mymap ['z'] = 3003;

 cout << "mymap contains:\n";

// This is where I stop understanding.
 highest = * mymap.rbegin ();          // last element
// What is the significance of calling it 'highest', when it is a
'reverse-end' iterator (which I take to mean an iterator to the element
before the first)?
 it = mymap.begin ();
 do
  cout << it->first << " => " << it->second << endl;
   while (mymap.value_comp () (* it ++, highest));
// What is the significance of the () before (* and after balue_comp? And
how does it accomplish this sorting that we see?
 
 return 0;
}

Output:
mymap contains:
x => 1001
y => 2002
z => 3003


__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind

Other related posts:

  • » map::value_comp in C++.