Jae said:
Hi
I wonder how can I implement the STL map sorting by value.
For example, I have a map m
map<int, int> m;
m[1] = 10;
m[2] = 5;
m[4] = 6;
m[6] = 1
and then.. I'd like to sort that with the m's value.
So, if I print the map, I'd like to get the result like
m[6] = 1
m[2] = 5
m[4] = 6
m[1] = 10
this.
How can I sort like this way?
I'm not 100% certain I understand what you mean by sort in this context.
Is there any way that I can deal with the key and value with sorted values?
What kind of container do you want to sort them in?
Could this possibly be what you're looking for?
-------------------------------------------------------------------
#include <iostream>
#include <map>
#include <utility>
typedef std::map<int,int> NormalMap;
typedef std::map< std:

air<int,int>, NormalMap::const_iterator >
ReverseMap;
int main() {
NormalMap m;
m[1] = 10;
m[2] = 5;
m[4] = 6;
m[6] = 1;
m[11] = 10;
// note second '10' value,
// but all keys are still unique
// if the NormalMap is going to change
// often in the code, then this might
// be better in a function
ReverseMap n;
for(NormalMap::const_iterator i=m.begin(); i!=m.end(); i++) {
// note that key,value has become
// value, key here
// each of these pairs will be
// unique, because the key
// from the NormalMap is
// unique
n[ std::make_pair(i->second,i->first) ] = i;
}
// the ReverseMap is ordered by the value,key from the
// NormalMap, and its mapped_type is a const_iterator
// to the NormalMap
for(ReverseMap::const_iterator i=n.begin(); i!=n.end(); i++) {
NormalMap::const_iterator j = i->second;
std::cout << "m[" << j->first
<< "] = " << j->second << ";"
<< std::endl;
}
}
--------------------------------------------------
And the output was:
-----------------------------
m[6] = 1;
m[2] = 5;
m[4] = 6;
m[1] = 10;
m[11] = 10;
------------------------------
You could also put the data from the NormalMap into a std::set,
reversing the key and value.
LR