题目:统计文本中单词出现频率前十的单词并打印到显示屏
老师,之前我写在另外一个博客的:http://blog.youkuaiyun.com/u012337099/article/details/40345925
其中包括了统计前十的单词以及用链表实现的统计出现频率最多的单词并打印,因为那个博客我已经不常用,所以转移到这个博客了
源代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include<iomanip>
#include<utility>
#include<algorithm>
using namespace std;
vector<pair<string,int>> word;
void findsameword(string Word);
bool sortWord(pair<string, int> elem1, pair<string, int> elem2);
void main()
{
system("color F1");
string temp;
ifstream TextFile;
TextFile.open("test.txt");
while (TextFile >> temp)
{
findsameword(temp);
}
sort(word.begin(), word.end(),sortWord);
cout << "出现单词频率前十的是:" << endl;
for (vector<pair<string, int>>::iterator itor = word.begin(); itor != word.begin()+10; itor++)
{
cout << "单词:" << setw(38) << setiosflags(ios::left) << itor->first << "数量:" << itor->second << endl;
}
system("pause");
}
void findsameword(string Word)
{
bool flag = false;
for (vector<pair<string,int>>::iterator itor = word.begin(); itor != word.end(); itor++)
{
if (Word == itor->first)
{
itor->second += 1;
flag = true;
}
}
if (!flag)
{
word.push_back(make_pair(Word, 1));
}
}
bool sortWord(pair<string, int> elem1, pair<string, int> elem2)
{
return elem1.second > elem2.second;
}
单词文本截图:
运行截图:
性能分析:
耗时较长,从一开始执行到结束共计耗费时间近1分钟
分析,程序中主要使用了C++函数pair以及sort函数,导致在排序上比较耗时间,也有可能是因为我在u盘上建立的工程,导致读写速度很慢,将工程转移到硬盘上:
发现计算时间仍然没有提升:
关闭排序函数,进行测试,发现与上面花费的时间几近,所以主要是在循环这里比较浪费时间。
后面发现这段代码其实做了很多额外功:
经过更改,在flag == true;添加一句:break;
void findsameword(string Word)
{
bool flag = false;
for (vector<pair<string,int>>::iterator itor = word.begin(); itor != word.end(); itor++)
{
if (Word == itor->first)
{
itor->second += 1;
flag = true;
break;
}
}
if (!flag)
{
word.push_back(make_pair(Word, 1));
}
}
分析:发现时间的占用少了很多(接近一半的时间)
相比之前我统计最多的单词的效率低了很多(之前的文本是350K左右,执行差不多3秒左右),之前我使用的是自己写的函数,利用链表完成的,这次我使用的是C++提供的容器Vector pair,没想到效率会低这么多,之后我还会尝试进行改进算法的执行效率,缩短程序执行时间,