tags:

views:

125

answers:

2

This program stores pairs in a map, counting the number of times a word occurs. The goal is to have the data sorted by number of occurences and output in value/string form. Obviously the normal map sorts by the string key, so I had to reverse it.

To do this I read in words, and increment their values appropriately in a map. Then I create a multimap and copy the pairs from the map into the multimap, but reversed. Then I iterate through the multimap, outputting the pairs. However, a runtime error occurs when I try to output the pairs and I'm not sure why.

Here is the code:

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

int main()
{
    map<string, int> words;
    multimap<int, string> words2;

    string s;
    while (true) {
        cin >> s;
        if (s == "0") break;
        ++words[s];
    }

    map<string, int>::iterator p;
    for (p = words.begin(); p!=words.end(); ++p)
        words2.insert(make_pair(p->second, p->first));

    multimap<int, string>::iterator p2;
    for (p2 = words2.begin(); p2!=words2.end(); ++p2)
        cout << p->first << ": " << p->second << '\n';
}

Any help is appreciated.

P.S. I read in different places that multimap can have multiple occurences of a key (which is why I used it in the first place) and/or multiple values in a single key. Some clarification would be nice regarding which is true or whether both are true.

Also is there any type of copy algorithm for maps? I decided to just use a for loop for simplicity's sake, and it would probably be fairly easy to write a custom copy, but I'm just wondering (for copying maps to other pair containers and copying to output.)

+2  A: 
 for (p2 = words2.begin(); p2!=words2.end(); ++p2)
        cout << p->first << ": " << p->second << '\n';

Shouldn't the p's in your output statement be p2's ?

anon
+2  A: 

You seem to use p rather than p2 when printing, Change the output line to:

cout << p2->first << ": " << p2->second << '\n';

This error would been avoided if you declared p in the for loop rather than before it since it would have gone out of scope after the first for loop ended.

Laserallan