954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

sorting stl::map

Does anyone know of a good way to sort an stl map?

I have something like the following example:

#include <iostream>
#include <map>
#include <algorithm>

int main() 
{
   map<int, float> map_to_sort;

   // Populate the map with between 20 - 2000 elements

   map_to_sort.sort(); 
}


Obviously I am aware that map<> doesn't have a sort function :op so does anyone have aquick method of sorting through a map?

From the best I can see I am going to have to manually iterate through all elements of the map and compare and move to a seperate map, I am hoping there is a better solution than this since that seems like a wasteful use of CPU time, this is for a searchengine project I am working on and as can be expected time is critical in this application, especially considering I actually need to sort through 3 seperate maps.

Any help would be really appreciated.

Best regards

Ben

liliafan
Junior Poster
117 posts since Apr 2004
Reputation Points: 66
Solved Threads: 3
 
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Hi Dave

I kinda figured there wasn't a sort() algorithm on map<> but I was hoping that maybe someone had written some efficient code to do a sort, and if so if they could give a few pointers on how it is achieved.

Thanks

Ben

liliafan
Junior Poster
117 posts since Apr 2004
Reputation Points: 66
Solved Threads: 3
 

Hi,
C++ Maps are sorted associative containers that contain unique key/value pairs. Maps are sorted by their keys.When you insert new data into the map,Map will sort automatically.So you no need separate function to sort the data in Map. Forgive me if you are searching any other kind of sort.

mn.balakumar
Newbie Poster
10 posts since Jan 2010
Reputation Points: 7
Solved Threads: 0
 

FYI, mn.balakumar, you missed the boat by almost six years. You're welcome to questions, but keep in mind that for each old thread you resurrect, a recent thread goes ignored by falling to the second page.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You