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 a quick 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

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

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.

Edited 6 Years Ago by mn.balakumar: n/a

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.

This article has been dead for over six months. Start a new discussion instead.