编写程序统计并输出所读入的单词出现的次数。
解答:
可以建立一个map对象,保存所读入的单词及其出现次数(以单词为键,对应的值为单词的出现次数)。
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string, int> wordCount;
string word;
//读入单词并统计其出现次数
cout<<"Enter some words(Ctrl+Z to end):"<<endl;
while(cin>>word)
{
++wordCount[word];//word的出现次数加1
}
//输出结果
cout<<"word\t\t"<<"times"<<endl;
for(map<string, int>::iterator iter=wordCount.begin(); iter!=wordCount.end(); ++iter)
{
cout<<(*iter).first<<"\t\t"<<(*iter).second<<endl;
}
return 0;
}
本文介绍了一个简单的C++程序,用于统计用户输入的单词出现频率,并使用map数据结构来记录每个单词及其对应的出现次数。
1301

被折叠的 条评论
为什么被折叠?



