编写一个程序,从键盘上输入一个个单词,每接收到一个单词后,输出该单词是否曾经出现过以及出现次数。可以尝试分别用多重集合(multiset)或映射(map)两种途径实现,将二者进行比较。本题答案你可以任意提交一种方法的代码。
时间: 2023-12-10 14:39:50 浏览: 191
使用multiset实现:
```cpp
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main()
{
multiset<string> words;
while(true)
{
string word;
cin >> word;
if(word == "exit") break;
words.insert(word);
int count = words.count(word);
if(count == 1) cout << word << " has appeared once." << endl;
else cout << word << " has appeared " << count << " times." << endl;
}
return 0;
}
```
使用map实现:
```cpp
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string, int> wordCount;
while(true)
{
string word;
cin >> word;
if(word == "exit") break;
wordCount[word]++;
if(wordCount[word] == 1) cout << word << " has appeared once." << endl;
else cout << word << " has appeared " << wordCount[word] << " times." << endl;
}
return 0;
}
```
两种方法的输出效果是一样的,但是使用map需要更多的代码来实现。multiset可以直接存储元素,并且提供了count函数用于查找元素出现的次数,而map需要先建立键和值之间的映射关系,然后才能通过键查找值。但是使用map可以方便地记录每个单词的出现次数,并且可以对单词按照出现次数排序。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)