Advertisement
oster_man

async KeyWords

Aug 18th, 2023
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <functional>
  2. #include <iostream>
  3. #include <map>
  4. #include <set>
  5. #include <future>
  6. #include <sstream>
  7. #include <string>
  8.  
  9. using namespace std;
  10.  
  11. struct Stats {
  12.     map<string, int> word_frequences;
  13.  
  14.     void operator+=(const Stats& other) {
  15.         for(const auto& [word,freq]:other.word_frequences){
  16.             word_frequences[word]+=freq;
  17.         }
  18.     }
  19. };
  20.  
  21. using KeyWords = set<string, less<>>;
  22.  
  23. Stats asyncExploreKeyWords(const KeyWords& key_words, istream& input) {
  24.     Stats word_freqs;
  25.  
  26.     future<Stats> asyncWordsFreq = async([&input,&key_words]{
  27.         Stats word_freqs;
  28.         for(string word;!input.eof();input>>word){
  29.                 if (key_words.count(word))
  30.                     ++(word_freqs.word_frequences[word]);
  31.             }
  32.         return word_freqs;
  33.         });
  34.  
  35.     return asyncWordsFreq.get();
  36. }
  37.  
  38. Stats ExploreKeyWords(const KeyWords& key_words, istream& input) {
  39.     Stats word_freqs;
  40.    
  41.     for (int core=0;core<2;++core){
  42.         word_freqs+=asyncExploreKeyWords(key_words,input);
  43.     }
  44.     return word_freqs;
  45. }
  46.  
  47. int main() {
  48.     const KeyWords key_words = {"yangle", "rocks", "sucks", "all"};
  49.  
  50.     stringstream ss;
  51.     ss << "this new yangle service really rocks\n";
  52.     ss << "It sucks when yangle isn't available\n";
  53.     ss << "10 reasons why yangle is the best IT company\n";
  54.     ss << "yangle rocks others suck\n";
  55.     ss << "Goondex really sucks, but yangle rocks. Use yangle\n";
  56.  
  57.     for (const auto& [word, frequency] : ExploreKeyWords(key_words, ss).word_frequences) {
  58.         cout << word << " " << frequency << endl;
  59.     }
  60.  
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement