Sort command for sorting a map<int, double> by key?

Suppose I have a map m defined in this way:

1
2
3
m[7] = 0.3,
m[0] = 9.5,
m[3] = 2.


Now I want to sort this map by key, so that it will appear like

1
2
3
m[0] = 9.5,
m[3] = 2.,
m[7] = 0.3


Does it exist a sort command that does this? How to apply it?
Thanks in advance! :)
std::map<Key, Value> is sorted by less<Key> by default: http://www.cplusplus.com/reference/map/map/

and if you want to custom compare:
http://stackoverflow.com/questions/5733254/create-an-own-comparator-for-map
Thank you! So this is the also the reason why map iterators iterate through the key (rather than the values), is it so?
iterators iterate (traverse) the container across the container elements, so you could:
1
2
3
4
5
6
7
8
9
10
11
12
13
 
std::map<int,double>::const_iterator itr;
// to reach the key and value of any given map element 
itr->first; itr->second; 
//or 
(*itr).first; (*itr).second; 
//another alternative to reach the key/value of any std::map element would be to use range loops (c++11):
std::map<int,double> myMap;
for (const auto& elem : myMap)
{
	elem.first;//key
	elem.second;//value
}
Last edited on
Topic archived. No new replies allowed.