Запишите карту в файл, используя for_each - PullRequest
0 голосов
/ 22 ноября 2018

Следующий код компилируется и выполняется, но в файл ничего не записывается, и я не могу понять, почему.Файл создается, но файл пуст.Я всегда удалял файл на всякий случай, но это не должно иметь значения

#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;
}

Ответы [ 2 ]

0 голосов
/ 22 ноября 2018

Мне нечего добавить к ответу @ snake_style, но я хотел бы отметить, что вы можете легко снизить сложность / затраты при использовании copy_if для фильтрации слов в sample_doc.txt, используяпростой while цикл:

#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();

    map<string, int> wordMap;
    ifstream words("sample_doc.txt");
    string s;

    while(words >> s) if (exclusionSet.count(s)==0) ++wordMap[s];

    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 голосов
/ 22 ноября 2018

Я бы предложил следующую версию исправлений

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;
}

Основные отличия:

  1. чтение данных из файла "sample_doc" в векторе строки , проверяя, входят ли они в набор исключений (исправьте ваш find_if call)
  2. формирование статистики частоты слов с помощью:

    for(auto &a : strings)
        wordMap[a] = wordMap[a] + 1;
    

И .... Я бы лучше заменил for_each на основанный на диапазоне для , например:

for(const auto &e: wordMap)
    out << e.first << " " << e.second << endl;
...