Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <functional>
- #include <iostream>
- #include <map>
- #include <set>
- #include <vector>
- #include <sstream>
- #include <string>
- #include <future>
- #include <algorithm>
- #include <execution>
- using namespace std;
- struct Stats {
- map<string, int> word_frequences;
- void operator+=(const Stats& other) {
- // сложить частоты
- for_each(execution::par, other.word_frequences.begin(), other.word_frequences.end(),
- [this](const pair<const string&, int>& pair) {
- word_frequences[pair.first] += pair.second;
- });
- }
- };
- using KeyWords = set<string, less<>>;
- vector<string> SplitIntoWords(const string& text) {
- vector<string> words;
- string word;
- for (const char c : text) {
- if (c == ' ') {
- if (!word.empty()) {
- words.push_back(word);
- word.clear();
- }
- } else {
- word += c;
- }
- }
- if (!word.empty()) {
- words.push_back(word);
- }
- return words;
- }
- Stats ExploreKeyWords(const KeyWords& key_words, istream& input) {
- Stats statistics;
- //auto async_for_each = async([&key_words, &statistics] {
- // for_each(execution::par, key_words.begin(), key_words.end(), [&statistics](const string& word) {
- // statistics.word_frequences[word];
- // });
- //});
- //vector<string> content;
- string content { istreambuf_iterator<char>(input), istreambuf_iterator<char>() }; // вся строка - текст внутри input
- //while (!input.eof()) {
- // string text;
- // getline(input, text);
- // content.push_back(text);
- //}
- //for (const string& text : content) {
- //}
- size_t middle = content.size() / 2;
- future<void> first_part = async([&statistics, &key_words, &content, middle] {
- Stats stats_one_string;
- for (const string& word : SplitIntoWords(content.substr(0, middle))) {
- if (key_words.count(word)) {
- stats_one_string.word_frequences[word]++;
- }
- }
- statistics += stats_one_string;
- });
- Stats stats_one_string;
- for (const string& word : SplitIntoWords(content.substr(middle))) {
- if (key_words.count(word)) {
- stats_one_string.word_frequences[word]++;
- }
- }
- statistics += stats_one_string;
- first_part.get();
- return statistics;
- }
- int main() {
- const KeyWords key_words = { "yangle", "rocks", "sucks", "all" };
- stringstream ss;
- ss << "this new yangle service really rocks\n";
- ss << "It sucks when yangle isn't available\n";
- ss << "10 reasons why yangle is the best IT company\n";
- ss << "yangle rocks others suck\n";
- ss << "Goondex really sucks, but yangle rocks. Use yangle\n";
- for (const auto& [word, frequency] : ExploreKeyWords(key_words, ss).word_frequences) {
- cout << word << " " << frequency << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment