Basically you need a Map that can store duplicate keys(int) in non-ascending order and values(string) in non-descending order.
I have a situation where I have to store marks of some students in descending order.
Use std::greater
so that the keys will be stored in descending order:
std::map<int, string, std::greater<int> > m;
But the problem arises when I have same mark for two students.
Use Multimap instead of Map. Multimap stores duplicate keys and that is its specialty.
std::multimap<int, string, std::greater<int> > m;
I have to then rank them on the basis of their name (Alphabetical order considering their name's first letter).
Store the value of identical-keys in map in a vector > sort the vector > insert the sorted vector back into map.
Note that, inside multimap, you don't need to worry about changing the keys or its order. Values are the only ones whose order is going to be changed (that too only within same-valued-key).
Demo
multimap<int, string, greater<int> >:: iterator it = m.begin(), st; //Stores duplicate keys(marks).
vector<string> vec;
int lastKey = INT_MAX;
while(it != m.end())
{
if(it->first < lastKey)
{
//Sort the Names
sort(vec.begin(), vec.end());
for(int i = 0; i < vec.size(); i++){
st->second = vec[i];
st++;
}
st = it;
vec.clear();
}
vec.push_back(it->second); //Insert name
lastKey = it->first; //marks of last inserted name.
it++;
}
//Do same for the last(lowest valued key in map) key.
sort(vec.begin(), vec.end());
for(int i = 0; i < vec.size(); i++){
st->second = vec[i];
st++;
}