How do I copy data from a map to a multiset?

What I am trying to do:
Counting the frequency of words occurring in a text file and printing them in order of frequency. I have successfully solved the problem using vectors (copying data from map to vector, then sorting). Now I am trying to do it with multiset, which should sort the data automatically (I think).

What my problem is:
The code that is written in bold; the back_inserter() does not seem to be functioning with multiset. Is there a function for this or a simpler way?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iterator>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <cctype>
#include <set>
#include <algorithm>

using namespace std;

string getNextWord(istream &in) { 	//Gets next word from inputFile.
	char c;
	string ans = "";
	c = in.get();
	while(!isalpha(c) && !in.eof()) {
		c=in.get();
	}
	while(isalpha(c)) {
		ans.push_back(tolower(c));
		c=in.get();
	}
	return ans;
}

int main() {
	map<string, int> words;
	multiset<pair<string, int> > words_m;
	ifstream inputFile("text.txt");	
	string nextWord;
	string empty = "";
	while((nextWord = getNextWord(inputFile)) != empty)
		++words[nextWord];		//Stores new word in map and increments value. 

	copy(words.begin(), words.end(), back_inserter(words_m)); //Copies from map to multiset.
	
	for(int i = words_m.size()-1; i > words_m.size()-20; --i)  //Prints it out.
        cout << words_m[i].first << " : " << words_m[i].second << endl;
	
}
Last edited on
Why use multiset? What is wrong with set? Also you never declared a variable called words_v.

there is no overload for the squarebrackets in multiset. And words_m stores pairs of type <string, int> but you are using it like it stores just integers
Last edited on
Topic archived. No new replies allowed.