Like Tree1Likes
  • 1 Post By laserlight

sorting map by value

This is a discussion on sorting map by value within the C++ Programming forums, part of the General Programming Boards category; Hi, a basic question how do i sort my map by value: example Code: map<int, int> m; m[1] = 10; ...

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

    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
    22,170
    Perhaps you should map the other way instead, or if you need both, then boost bimap could be useful.
    baxy likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    176
    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
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    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, 06:20 PM
  2. Sorting
    By MarlonDean in forum C++ Programming
    Replies: 9
    Last Post: 05-16-2008, 02:56 AM
  3. Sorting...
    By Aakash Datt in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2003, 10:02 PM
  4. Help with sorting
    By aba_abstract2k in forum C++ Programming
    Replies: 10
    Last Post: 07-12-2002, 11:55 PM
  5. Sorting words with a fast, effincient sorting method
    By Unregistered in forum C++ Programming
    Replies: 19
    Last Post: 07-12-2002, 05:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21