CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2009
    Posts
    2

    How do i sort a STL Map?

    I have an STL map using int key and int value. How do i sort the map from smallest to largest based on it's value without losing the associated key. Then return the keys in that order? ( i want to then push the keys onto a queue).

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: How do i sort a STL Map?

    Maps are automatically sorted by key. If your primary need is to be able to sort by value, then you should consider whether you've defined the map backwards.

    If you need at various times to view the objects in both orderings, then you should consider a data structure which captures this relation a bit better than a std::map. The most trivial example of such would be a class simply wrapping both a map<A,B> and a map<B,A>, which contain identical pairs of data at all times. Another approach would be to use a boost::bimap.

  3. #3
    Join Date
    Jul 2009
    Posts
    2

    Re: How do i sort a STL Map?

    I have solved the problem. A multimap (instead of a map) resolved the issues of having duplicate keys. Like you said Lindley, I inversed the elements in the multimap (i.e. put the values that required sorting into the key, and put the keys as values). That way when the container is sorted via its keys, then i can then simply push my values (which are the indexes that i am after), back onto the queue.

    For curiousities sake, this seems to be an effective and efficient way of prioritising a pending list based on their cost for pathfinding purposes (which is where i have applied the multimap).

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: How do i sort a STL Map?

    Priority queues (and there's one in the STL, by the way) are usually based on heaps rather than trees, since a full sort is not required. The difference in efficiency is minor but present.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured