RE: :value_comp in C++.

  • From: "Ken Perry" <whistler@xxxxxxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Thu, 1 Nov 2007 23:59:36 -0700


It doesn't do what you think that is why your having trouble.  First off the
rbegin actually returns the highest element in the keys of the map.  In this
case it returns 'Z'  note though it doesn't return the .end element.  There
is a slight difference.  This code also does not sort the items it just
starts at the first item which is it=mymap.begin;  and spins to the highest
key which is 'z'.  As for what the () is that is there because the comp
value is a method to compare the values of both the it and the highest.  So
what he is really doing is checking to see if they got to the end of the
maps.  

If I understand you right you want to sort them in order of the number and
this code doesn't do that at all.  Just move the 2002 to X and the 1001 to y
and run it and you will see it doesn't sort it at all.  If I understand what
you want to do right then tell me and I can probably write up some code that
will do what you want.

Ken 

-----Original Message-----
From: programmingblind-bounce@xxxxxxxxxxxxx
[mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of Graham Hardy
Sent: Thursday, November 01, 2007 10:47 PM
To: programmingblind@xxxxxxxxxxxxx
Subject: map::value_comp in C++.

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

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

Other related posts: