Link to home
Start Free TrialLog in
Avatar of polkadot
polkadot

asked on

Sort a map in C++ by value not by key: map<char, int>

given:

map<char, int> table;

contains:

A 23
B 2
C 26
D 12


I want to have a function that outputs using cout or any ostream:

C 26
A 23
D 12
B 2



SOLUTION
Avatar of 0xC0DEB07
0xC0DEB07

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oops, corection, that should have been

map<int, char>::iterator i2 = tmp.begin();

while (i2 != tmp.end()) {

  cout << i2->first << " <-> " i2->second << endl;

  ++i2;
}
Avatar of polkadot
polkadot

ASKER

gives me an incomplete output:

for the map:

a 4
b 2
c 2
d 2
f 4

this code gave me:

2 b
4 a

its replacing the 4 f with teh 4 a ... and the 2 c and 2 d with the 2 b...

I hate to say that, but I get

#include <map>
#include <iostream>
using namespace std;

int main () {

map<char, int> table;

table.insert(map<char, int>::value_type('A',23));
table.insert(map<char, int>::value_type('B',2));
table.insert(map<char, int>::value_type('C',26));
table.insert(map<char, int>::value_type('D',12));

map<int, char> tmp;
map<char, int>::iterator i1 = table.begin();

while (i1 != table.end()) {

  tmp.insert(map<char, int>::value_type(i1->second,i1->first));

  ++i1;
}

map<int, char>::iterator i2 = tmp.begin();

while (i2 != tmp.end()) {

  cout << i2->first << " <-> " << i2->second << endl;

  ++i2;
}

return 0;
}

2 <-> B
12 <-> D
23 <-> A
26 <-> C

which to me seems to be what you want.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Joaquín M López Muñoz has build a bimap class which does have the ability to retrieve keys by value.
See following link for more information and source code:

http://www.codeproject.com/vcpp/stl/bimap.asp
jkr and I have answered his question ..

regards,Ahmad;
Little late now, but IMHO, the link I provided really answred the question.
It gives the functionallity the questioner was looking for.