fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. struct Words {
  9. string s;
  10. unsigned count;
  11. };
  12.  
  13. bool compareWords(Words& w1, Words& w2) {
  14. return w1.count > w2.count;
  15. }
  16.  
  17. int main() {
  18. string s;
  19. vector<Words> WordCount;
  20. vector<string> all_words;
  21.  
  22. while (cin >> s) {
  23. all_words.push_back(s);
  24. }
  25. sort(all_words.begin(), all_words.end());
  26.  
  27. int count = 1;
  28. for (int i = 1; i < all_words.size(); ++i) {
  29. if (all_words[i] != all_words[i - 1]) {
  30. //Пришлось чуть помощи у chatgpt попросить, не знал как проверить наличие слова в структуре
  31. auto it = find_if(WordCount.begin(), WordCount.end(), [all_words, i](Words& w) { return w.s == all_words[i - 1]; });
  32. if (it != WordCount.end()) {
  33. it->count += count;
  34. }
  35. else {
  36. WordCount.push_back({all_words[i - 1], count});
  37. }
  38. count = 1;
  39. }
  40. else {
  41. count++;
  42. }
  43. }
  44. //и тут
  45. auto it = find_if(WordCount.begin(), WordCount.end(), [all_words](Words& w) { return w.s == all_words.back(); });
  46. if (it != WordCount.end()) {
  47. it->count += count;
  48. }
  49. else {
  50. WordCount.push_back({all_words.back(), count});
  51. }
  52.  
  53. sort(WordCount.begin(), WordCount.end(), compareWords);
  54. for (Words w : WordCount) {
  55. cout << w.s << ' ';
  56. }
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5312KB
stdin
A fly flies but flies fly too  a a a a A 
stdout
a A flies fly but too