STL--for_each 统计单词出现次数

#include <iostream> #include <string> #include <map> #include <fstream> #include <algorithm> #include <ctime> using namespace std; map<string , int> m; void print( const pair<string, int> &r) { cout << r.first << " " << r.second << endl; } void record( const string &s) { m[ s ] ++; } int main() { double beginTime = clock(); fstream in("source.txt"); istream_iterator<string> ii(in); istream_iterator<string>eos; for_each(ii,eos,record); for_each( m.begin(), m.end(), print); double endTime = clock(); cout << " time: " << endTime - beginTime << " ms" << endl; return 0; } //我的电脑,一样的文件17833ms /* #include <time.h> #include <map> #include <string> #include <fstream> #include <iostream> using namespace std; int main() { double beginTime = clock(); ifstream in("source.txt"); map<string, int> M; map<string, int>::iterator j; string t; while( in >> t ) { M[t]++; } for ( j = M.begin(); j != M.end(); j++) { cout << j->first << " " << j->second << endl; } double endTime = clock(); cout << "time: " << endTime - beginTime << "ms " << endl; return 0; } //我的电脑,一样的文件17945ms //差别不大,但是C++的输入输出严重影响的效率,如果用C语言实现,同样的数据,时间不会超过2000ms */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值