|
|
发表于 2021-3-25 16:47:04
|
显示全部楼层
本楼为最佳答案
 一言难尽,我相当于重写了,你参考下吧...
- #include<iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- using namespace std;
- struct WORD
- {
- string word;
- int count = 1;
- bool operator()(const WORD& a, const WORD& b)
- {
- return a.word < b.word;
- }
- };
- void input(vector<WORD>& words)
- {
- char c;
- string temp;
- WORD tWord;
- cout << "输入几个英语单词:";
- //从这里开始就不对,不要用cin....
- //题目上说单词中间是空格隔开
- //不是回车区分单词
- while (c = getchar())
- {
- if ((c >= 'A' && c <= 'Z') || c >= 'a' && c <= 'z')
- temp.append(1, c);
- else if (c == ' ' || c == '0')
- {
- tWord.word.assign(temp);
- words.push_back(tWord);
- temp = "";
- if (c == '0')
- break;
- }
- }
- }
- void order(vector<WORD>& words)
- {
- //去重
- for (int i = 0; i < words.size() - 1; ++i)
- {
- for (int j = i + 1; j < words.size(); ++j)
- {
- if (words[i].word == words[j].word)
- {
- words[i].count += 1;
- words.erase(words.begin() + j);
- j -= 1;
- }
- }
- }
- //排序
- sort(words.begin(), words.begin() + words.size(), WORD());
- }
- void VectorPrint(const vector<WORD>& words)
- {
- for (const auto& item : words)
- {
- printf_s("%s : %d\n", item.word.c_str(), item.count);
- }
- }
- int main()
- {
- vector<WORD> words;
- input(words);
- order(words);
- VectorPrint(words);
- return 0;
- }
复制代码
|
-
调试输出
|