我正在使用以下代码来计算单词的出现频率:
// Briana Morrison为Owen编写的程序
//#pragma warning (disable : 4786)
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
// program assumes that the filename is the only thing passed into program
// if you are using standard argc and argv, then arguments to main should change, and uncomment
// first line.
int main(int argc, char * argv[])
{
string filename(argv[1]);
// string filename;
//cout << "Enter filename" << endl;
//cin >> filename;
ifstream infile(filename.c_str());
//ifstream infile("poe.txt");
string word;
bool debug = false; // for debugging purposes
int count = 0; // count of words for debugging
// create a map of words to frequencies
map<string, int, less<string> > words;
// create a multimap of frequencies to words
multimap<int, string, greater<int> > freq;
// loop while there is input in the file
infile >> word; //priming read
while (infile)
{
count++;
// convert word to lowercase
for (int i = 0; i < word.length(); i++)
if ('A' <= word[i] && word[i] <= 'Z')
word[i] = tolower(word[i]);
if (debug) cout << word << endl;
// if word not found, add to map, otherwise increment count
if (words.find(word) != words.end())
{
words[word]++;
if (debug) cout << word << " found and count incremented to " << words[word] << endl;
}
else
{
words[word] = 1;
if (debug) cout << word << " not found and count incremented to " << words[word] << endl;
}
infile >> word;
}
if (debug) cout << "count is " << count << " and map has " << words.size() << endl;
// now go through map and add everything to multimap...words still in alphabetical order
map<string, int, less<string> >::iterator it = words.begin();
for (it = words.begin(); it != words.end(); it++)
{
pair<int, string> p(it->second, it->first);
freq.insert(p);
}
if (debug) cout << "map has " << words.size() << " and multimap has " << freq.size() << endl;
ofstream outfile("myout.txt");
multimap<int, string, greater<int> >::iterator myit=freq.begin();
for (myit = freq.begin(); myit != freq.end(); myit++)
{
outfile << myit->first << "\t" << myit->second << endl;
}
outfile.close();
return 0;
}
我想问题不在这里
当我将单词写入文件时,每次迭代都会变慢,为什么呢?
ofstream outfile("myout.txt");
multimap<int, string, greater<int> >::iterator myit=freq.begin();
for (myit = freq.begin(); myit != freq.end(); myit++)
{
outfil<< myit->first << "\t" << myit->second << endl;
}
outfile.close();
如何快速将多图写入文件?
最佳答案
您可以使用'\n'
而不是 std::endl
来避免每行都刷新它。
outfil << myit->first << '\t' << myit->second << '\n';
关于c++ - 将 multimap 写入文件Fastway C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20606797/