Thread: sorting map by value

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    222

    sorting map by value

    Hi,

    a basic question how do i sort my map by value:

    example


    Code:
    map<int, int> m;
    m[1] = 10;
    m[3] = 10;
    m[6] = 5;
    m[12] = 14;
    what i need is :



    Code:
    m[12] = 14;
    m[3] = 10;
    m[1] = 10;
    m[5] = 6;
    so if i have duplicate values then key order should be considered. well i'll figure out the key order latter, for now i would appreciate some basic help with value order. I mean i could first copy the values int a vector and the sort the vector and then reassign key values but that sounds complicated. is there a faster (or at least a simpler ) way to do this. all i need to know is the order of keys give the values are sorted (biggest to smallest)

    thnx

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Perhaps you should map the other way instead, or if you need both, then boost bimap could be useful.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    222
    Quote Originally Posted by laserlight View Post
    Perhaps you should map the other way instead, or if you need both, then boost bimap could be useful.
    ok that was an obvious one. plus i can use multimap not to lose repeated values. sorry for wasting time.

    thnx

  4. #4
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Since a map is accessed by key I fail to see what sorting it accomplishes.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 21
    Last Post: 07-15-2012, 05:20 PM
  2. Sorting
    By MarlonDean in forum C++ Programming
    Replies: 9
    Last Post: 05-16-2008, 01:56 AM
  3. Sorting...
    By Aakash Datt in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2003, 09:02 PM
  4. Help with sorting
    By aba_abstract2k in forum C++ Programming
    Replies: 10
    Last Post: 07-12-2002, 10:55 PM
  5. Sorting words with a fast, effincient sorting method
    By Unregistered in forum C++ Programming
    Replies: 19
    Last Post: 07-12-2002, 04:21 PM