Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting in std::map where key is a std::string

Tags:

I have a std::map mymap

Now, if I insert values in the map like:

std::map <string, string> mymap; mymap["first"] = "hi"; mymap["third"] = "how r you"; mymap["second"] = "hello"; 

Now I want to iterate over the map and print the value in sorted(keys) manner:

map<string, string>::iterator itr; for(itr = mymap.begin(); itr != mymap.end(); itr++) {    string newline = itr->second;    cout << newline << endl; } 

Output should be:

hi  hello  how r you  

I thought that by default map stores in sorted keys manner but I'm getting the same order in output as I'm giving in input. Do I need to provide my sort function for this or need to do something extra before iterating over the map?

like image 998
Ruchi Avatar asked Dec 13 '11 13:12

Ruchi


People also ask

Does std::map Sort by key?

Entries in std::map are ordered by the key, or itr->first.

Can you sort a map by key in C++?

A map consists of key/value pairs. Each pair is an element. All keys in a map are unique. A map can be sorted by keys.

Are maps sorted by key or value C++?

No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.


1 Answers

The elements in std::map are ordered (by default) by operator< applied to the key.

The code you posted, with minor edits, worked for me as you expected:

std::map <string, string> mymap; mymap["first"]="hi"; mymap["third"]="how r you"; mymap["second"]="hello";  for (std::map<string, string>::iterator i = mymap.begin(); i != mymap.end(); i++) {     cout << i->second << "\n"; } 

Prints:

hi hello how r you 
like image 198
hmjd Avatar answered Oct 31 '22 16:10

hmjd