下面的代码可以编译和执行,但是什么也没有写到文件中,我一生都无法弄清楚为什么。正在创建文件,但该文件为空。我确保每次都删除该文件,以防万一,但这不会有所不同
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <map>
#include <set>
using namespace std;
int main(){
set<string> exclusionSet;
ifstream stopWords("stopwords.txt");
copy(istream_iterator<string>(stopWords),
istream_iterator<string>(),
inserter(exclusionSet, exclusionSet.end()));
stopWords.close();
//for_each(exclusionSet.begin(),
// exclusionSet.end(),
// [](const string& s){cout<<s<<endl;});
map<string, int> wordMap;
ifstream words("sample_doc.txt");
copy_if(istream_iterator<string>(words),
istream_iterator<string>(),
inserter(exclusionSet, exclusionSet.end()),
[=](const string& s){return exclusionSet.find(s)!=exclusionSet.end();});
ofstream out("frequency.txt");
for_each(begin(wordMap),
end(wordMap),
[&out](const pair<const string, int>& e){ out<<e.first<<" "<<e.second<<endl;});
out.close();
return 0;
}
答案 0 :(得分:0)
我建议使用以下版本的修补程序
int main()
{
map<string, int> wordMap;
set<string> exclusionSet;
ifstream stopWords("stopwords.txt");
copy(istream_iterator<string>(stopWords), istream_iterator<string>(), inserter(exclusionSet, exclusionSet.end()));
stopWords.close();
vector<string> strings;
ifstream words("sample_doc.txt");
copy_if(istream_iterator<string>(words), istream_iterator<string>(), inserter(strings, strings.end()),
[=](const string& s)
{
return exclusionSet.find(s) == exclusionSet.end();
});
words.close();
for(auto &a : strings)
wordMap[a] = wordMap[a] + 1;
ofstream out("frequency.txt");
for_each(begin(wordMap), end(wordMap),
[&out](const pair<const string, int>& e)
{
out << e.first << " " << e.second << endl;
});
out.close();
return 0;
}
主要区别:
形成单词的频率统计信息:
for(auto &a : strings)
wordMap[a] = wordMap[a] + 1;
然后...。我宁愿将 for_each 替换为基于范围的 for ,例如:
for(const auto &e: wordMap)
out << e.first << " " << e.second << endl;
答案 1 :(得分:0)
除了@snake_style的答案之外,我没有太多要添加的内容,但是我想指出的是,您可以轻松地降低使用copy_if
来过滤{{1}中的单词的复杂性/费用},方法是使用简单的sample_doc.txt
循环:
while