给定一个单词数组wordList,每个单词最多包含30个字符,列表中最多包含1000个单词。请编写程序void WordStatic(charwordList[],int n,Wordwds,int&cnt),统计每个单词出现次数放入数组wds中,并将数组wds中的元素按出现的次数从高到低排序,其中n表示wordList中的元素个数,cnt表示wds中的元素个数,即出现的单词个数。最后用 int main ()实现整个程序
时间: 2024-02-05 16:10:57 浏览: 66
rb-wordlist-generator:一个简单的用于创建单词表的Ruby工具
下面是代码实现:
```c++
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
struct Word {
string str;
int count;
Word(string s, int c): str(s), count(c) {}
};
bool cmp(const Word& w1, const Word& w2) {
return w1.count > w2.count;
}
void WordStatic(string wordList[], int n, Word wds[], int& cnt) {
unordered_map<string, int> wordMap;
for (int i = 0; i < n; i++) {
if (wordMap.find(wordList[i]) != wordMap.end()) {
wordMap[wordList[i]]++;
} else {
wordMap[wordList[i]] = 1;
}
}
cnt = 0;
for (auto it = wordMap.begin(); it != wordMap.end(); it++) {
wds[cnt++] = Word(it->first, it->second);
}
sort(wds, wds + cnt, cmp);
}
int main() {
string wordList[] = {"hello", "world", "hello", "world", "hello", "cpp", "cpp", "java", "python"};
int n = sizeof(wordList) / sizeof(wordList[0]);
Word wds[n];
int cnt;
WordStatic(wordList, n, wds, cnt);
for (int i = 0; i < cnt; i++) {
cout << wds[i].str << ": " << wds[i].count << endl;
}
return 0;
}
```
我们使用了一个哈希表来存储每个单词的出现次数,然后将哈希表中的元素拷贝到一个结构体数组中,并按照出现次数从高到低排序。最后在main函数中调用WordStatic函数进行测试。
阅读全文