KNU
KNU

Reputation: 2515

How to compare VALUE in multimap

I learnt multimaps are <key,value> pair which allows duplicate keys (unlike maps). Help me to sort a multimap first by key(which happens automatically) and then by value(i.e name).

int main()
{
multimap<int,string>info; // <key,value>
char name[10000];
int age;

//Input till EOF
while (std::cin >> name >> age){                  
info.insert( pair<int,string>(age,name) );
}

//sorted output according to key i.e age
map<int,string> :: iterator i;
for(i=info.begin(); i !=info.end(); i++)
    cout<<(*i).second<<endl;
}

Input:

DUCHESS 26
MARIE 8
BERLIOZ 8
TOULOUSE 7
THOMAS 28

Output:
TOULOUSE 7
BERLIOZ 8
MARIE 8
DUCHESS 26
THOMAS 28

Here ages(integers) are keys, so its is first sorted wrt age but if two or more age are same as in BERLIOZ and MARIE then BERLIOZ is desired to be printed before MARIE since B is alphabetically superior than M.

Upvotes: 1

Views: 1499

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37132

A multimap only sorts the keys, not the values.

There are a number of ways you could approach a solution. One way is to go back to using a map, but store a set rather than a string. This way you get sorting on both keys and the strings within each set.

int main()
{
    map<int,set<string>> info;
    char name[10000];
    int age;

    //Input till EOF
    while (std::cin >> name >> age) {
        info[age].insert(name);
    }

    // sorted output
    map<int,set<string>>::iterator i;
    for (i = info.begin(); i != info.end(); ++i)
    {
        set<string>::iterator j;
        for (j = i->second.begin(); j != i->second.end(); ++j)
            cout << *j << i->first << endl;
    }
}

The limitation of using a set is that the values within a set must be unique, so if you have two people with the same name and age it won't work. If that's an issue, you could change to using a multiset, or use a list and sort the list using std::sort once all the names are added to it.

Upvotes: 2

Related Questions