编写一个程序,从键盘上输入一个个单词,每接收到一个单词后,输出该单词是否曾经出现过以及出现次数。用多重集合(multiset)
时间: 2024-02-13 09:00:39 浏览: 18
好的,以下是 C++ 代码实现:
```C++
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <iterator>
#include <set>
int main() {
std::unordered_map<std::string, int> word_count; // 统计每个单词的出现次数
std::set<std::string> word_set; // 存储已经出现过的单词
std::string word;
while (std::cin >> word) {
auto it = word_count.find(word);
if (it != word_count.end()) { // 如果该单词已经出现过
std::cout << "Word " << word << " has appeared " << it->second << " times." << std::endl;
++it->second;
} else {
std::cout << "Word " << word << " has never appeared before." << std::endl;
word_count.insert({word, 1});
word_set.insert(word);
}
}
std::cout << "All distinct words that have appeared:" << std::endl;
std::copy(word_set.begin(), word_set.end(), std::ostream_iterator<std::string>(std::cout, " "));
std::cout << std::endl;
return 0;
}
```
采用了 `std::unordered_map` 统计每个单词的出现次数,采用 `std::set` 存储已经出现过的单词。在输入每个单词时,先在 `word_count` 中查找该单词是否已经出现过,如果已经出现过,则输出该单词的出现次数并将其次数加一;否则,输出该单词还未出现过,并将其加入到 `word_count` 和 `word_set` 中。最后输出所有出现过的单词。