fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. #include <type_traits>
  6. #include <sstream>
  7. #include <string>
  8. #include <map>
  9. #include <cmath>
  10. using namespace std;
  11. class Word
  12. {
  13. public:
  14. std::string Token;
  15. int Count;
  16.  
  17. Word (const std::string &token, int count)
  18. : Token(token), Count(count) {}
  19. };
  20. int main ()
  21. {
  22. std::map<std::string, int> FileA;
  23. std::map<std::string, int> FileB;
  24.  
  25. //Read the input faking a ifstream...
  26. std::string file;
  27. std::getline(std::cin,file);
  28. std::stringstream ssa (file);
  29. while (ssa.good ())
  30. {
  31. std::string token;
  32. ssa >> token;
  33. ++FileA[token];
  34. }
  35.  
  36. std::getline(std::cin,file);
  37. std::stringstream ssb (file);
  38. while (ssb.good ())
  39. {
  40. std::string token;
  41. ssb >> token;
  42. ++FileB[token];
  43. }
  44.  
  45. std::vector<Word> intersection;
  46.  
  47. for (auto i = FileA.begin(); i != FileA.end (); ++i)
  48. {
  49. auto bentry = FileB.find (i->first); //Look up the word from A in B
  50. if (bentry == FileB.end ())
  51. {
  52. continue; //The word from file A was not in file B, try the next word
  53. }
  54.  
  55. //We found the word from A in B
  56. intersection.push_back(Word (i->first,std::min(i->second,bentry->second))); //You can replace the std::min call with whatever method you want to qualitate "most common"
  57. }
  58.  
  59. //Now sort the intersection by Count
  60. std::sort (intersection.begin(),intersection.end(), [](const Word &a, const Word &b) { return a.Count > b.Count;});
  61.  
  62. for (auto i = intersection.begin (); i != intersection.end (); ++i)
  63. {
  64. std::cout << (*i).Token << ": " << (*i).Count << std::endl;
  65. }
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 3044KB
stdin
apple apple apple banana
apple apple banana orange orange orange orange orange
stdout
apple: 2
banana: 1