// PE3-3--写一个程序,计算输入中每个不同的单词出现了多少次
// 时间:2012-12-19 11:02:35
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using std::cin; using std::endl;
using std::cout; using std::vector;
using std::sort; using std::string;
int main()
{
cout << "请输入一段文字:" << endl;
string words;
vector<string> texts;
// 不变式:到目前为止,texts包含了所有的单词数
while (cin >> words && (words != "EOF"))
{
texts.push_back(words);
}·
// 给输入的单词排序
sort(texts.begin(), texts.end());
// 获取总的单词个数
typedef vector<string>::size_type vec_sz;
vec_sz size = texts.size();
// 单词出现次数
vec_sz cnt;
vector<vec_sz> count;
// 不重复的单词
string words2;
vector<string> texts2;
cnt = 0;
words2 = texts[0];
texts2.push_back(words2);
for (vec_sz i=0; i != size; i++)
{
if (words2 == texts[i])
{
cnt++;
}
else
{
count.push_back(cnt);
words2 = texts[i];
texts2.push_back(words2);
cnt = 1;
}
}
cout << "出现的单词和对应的次数是:" << endl;
vec_sz count_sz = count.size();
for (vec_sz j=0; j != count_sz; ++j)
{
cout << texts2[j] <<" "<< count[j] << "次" << endl;
}
return 0;
}
一道练习题,就是如何使用vector标准容器来实现统计单词的个数,那么我的思路是:
1:首先利用sort函数对其进行排序(标准库的sort效率应该会很高吧!!)
2:利用3个Vector容器。
1)第一个存放输入的数据;
2) 第二个存放所有不重复的单词;
3) 第三个存放重复单词对应的个数。
由于经过排序后,所有相同的单词均排在一起,那么我们就可以很容易的获得不同单词出现的个数。
(未完待续)
本文介绍了一个使用C++实现的程序,该程序通过标准输入读取文本,并统计每个不同单词出现的次数。采用vector容器存储单词,利用sort进行排序,然后遍历计数。
1929





