编写一个程序,从键盘上输入一个个单词,每接收到一个单词后,输出该单词是否曾经出现过以及出现次数。可以尝试分别用多重集合(multiset)或映射(map)两种途径实现,将二者进行比较。本题答案你可以任意提交一种方法的代码。 注:输入一个单词并回车,立即输出出现的次数(用times:次数)表示。输入#结束。 参考的输入输出如下(下面单数行为输入,双数行为输出): hello times:0 world times:0 hello times:1 hello times:2 #
时间: 2024-02-11 18:06:54 浏览: 23
以下是使用 multiset 实现的程序代码:
```C++
#include <iostream>
#include <string>
#include <set>
int main() {
std::multiset<std::string> words; // 多重集合,用于存储单词
std::string word; // 临时存储输入的单词
while (std::cin >> word && word != "#") {
auto iter = words.find(word); // 查找单词在多重集合中的位置
if (iter == words.end()) { // 如果该单词没有出现过
std::cout << word << " times:0" << std::endl;
words.insert(word); // 将单词插入到多重集合中
} else { // 如果该单词已经出现过
std::cout << word << " times:" << words.count(word) << std::endl;
}
}
return 0;
}
```
以下是使用 map 实现的程序代码:
```C++
#include <iostream>
#include <string>
#include <map>
int main() {
std::map<std::string, int> word_counts; // 映射,用于存储每个单词出现的次数
std::string word; // 临时存储输入的单词
while (std::cin >> word && word != "#") {
auto iter = word_counts.find(word); // 查找单词在映射中的位置
if (iter == word_counts.end()) { // 如果该单词没有出现过
std::cout << word << " times:0" << std::endl;
word_counts[word] = 1; // 将单词插入到映射中,并将出现次数设置为 1
} else { // 如果该单词已经出现过
std::cout << word << " times:" << iter->second << std::endl;
iter->second++; // 将该单词的出现次数加 1
}
}
return 0;
}
```
两种方法的区别同上,只是在输出时需要额外加上单词本身。注意在读取输入时,需要判断输入的单词是否为 "#",如果是则结束循环。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)