鱼C论坛

 找回密码
 立即注册
查看: 2775|回复: 3

[已解决]请各位帮忙检查这段C++作业代码。

[复制链接]
发表于 2021-3-25 16:47:04 | 显示全部楼层    本楼为最佳答案   
一言难尽,我相当于重写了,你参考下吧...
  1. #include<iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>

  5. using namespace std;

  6. struct WORD
  7. {
  8.     string word;
  9.     int count = 1;

  10.     bool operator()(const WORD& a, const WORD& b)
  11.     {
  12.         return a.word < b.word;
  13.     }
  14. };

  15. void input(vector<WORD>& words)
  16. {
  17.     char c;
  18.     string temp;
  19.     WORD tWord;
  20.     cout << "输入几个英语单词:";
  21.     //从这里开始就不对,不要用cin....
  22.     //题目上说单词中间是空格隔开
  23.     //不是回车区分单词
  24.     while (c = getchar())
  25.     {
  26.         if ((c >= 'A' && c <= 'Z') || c >= 'a' && c <= 'z')
  27.             temp.append(1, c);
  28.         else if (c == ' ' || c == '0')
  29.         {
  30.             tWord.word.assign(temp);
  31.             words.push_back(tWord);
  32.             temp = "";
  33.             if (c == '0')
  34.                 break;
  35.         }
  36.     }
  37. }

  38. void order(vector<WORD>& words)
  39. {
  40.     //去重
  41.     for (int i = 0; i < words.size() - 1; ++i)
  42.     {
  43.         for (int j = i + 1; j < words.size(); ++j)
  44.         {
  45.             if (words[i].word == words[j].word)
  46.             {
  47.                 words[i].count += 1;
  48.                 words.erase(words.begin() + j);
  49.                 j -= 1;
  50.             }
  51.         }
  52.     }

  53.     //排序
  54.     sort(words.begin(), words.begin() + words.size(), WORD());
  55. }

  56. void VectorPrint(const vector<WORD>& words)
  57. {
  58.     for (const auto& item : words)
  59.     {
  60.         printf_s("%s : %d\n", item.word.c_str(), item.count);
  61.     }
  62. }

  63. int main()
  64. {
  65.     vector<WORD> words;
  66.     input(words);
  67.     order(words);
  68.     VectorPrint(words);

  69.     return 0;
  70. }
复制代码

调试输出

调试输出
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-4-2 00:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表