468,248 Members | 1,530 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,248 developers. It's quick & easy.

can I rely on the sorting of std::map<>

63
I have some data in a map and I want to sort it. Currently I have implemented it like this:


Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5.  
  6. int main(){
  7.  
  8.   // some data
  9.   map<string, double> myList;
  10.   myList["peter"]= 3.0;
  11.   myList["paul"]= 1.0;
  12.   myList["mary"] = 2.0;
  13.  
  14.   // sort the elements
  15.   map<double, string> mySortedList;
  16.   for ( map<string, double>::iterator i = myList.begin();
  17.     i != myList.end();
  18.     i++ )
  19.     {
  20.       mySortedList[ i->second ] = i->first;
  21.     }
  22.  
  23.   // print the sorted elements
  24.   cout << "sorted: ";
  25.   for ( map<double, string>::iterator i = mySortedList.begin();
  26.     i != mySortedList.end();
  27.     i++ )
  28.     {
  29.       cout << i->first << " {" << i->second << "} ";
  30.     }
  31.   cout << "\n";
  32.  
  33. }
  34.  

And it works as I expect it with g++ 3.4.4 cygwin, but I'm anxious since
http://www.cppreference.com/cppmap/index.html
only says that maps are sorted, but not whether that is ascending or descending or whatever-map-blackmagic-sorting.

Anybody able to clarify this?
Dec 11 '07 #1
2 2473
weaknessforcats
9,207 Expert Mod 8TB
maps are sorted.

They are sorted by the operator< of the class used as the key.

If there is no operator< for the class used as a key, you can write an operator< that takes two key valus as argument and returns a bool.

OR, you can write any function that takes two key objects, compares them and returns a bool.

The sequence you get is determined by the comparision function and not by the map.

The map template has:

map<key, value, func>

where key is the key object, valus is the object associated with the key, and func is a binary predicate. In STLspeak, a binary predicate is a function thay takes two arguments and returns a bool. For example, yo use any old compare function, you could:

Expand|Select|Wrap|Line Numbers
  1. map<int, string, Ascending> myMap;
  2.  
  3. bool Ascending(int first, int second)
  4. {
  5.     return first < second;
  6. }
  7.  
  8. OR:
  9.  
  10. map<int, string, Descending> myMap;
  11.  
  12. bool Descending(int first, int second)
  13. {
  14.     return first > second;
  15. }
  16.  
Dec 11 '07 #2
jabbah
63
ok, got it, thank you
Dec 12 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

19 posts views Thread by Erik Wikström | last post: by
6 posts views Thread by Juha Nieminen | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.