读文件,判断单词出现个数(c++实现)

这个版本为区分大小写的实现(代码可直接通过编译):

#include <iostream>
#include <fstream>
#include <map>
#include <string.h>
#ifndef foreach
#define foreach(container,it) \
    for(typeof((container).begin()) it = (container).begin();it != (container).end();++it)
#endif //foreach
using namespace std;
int main(int argc,char* argv[])
{
    if(argc < 2){
        cerr << "usage" << argv[0] << "   filename " << endl;
        return -1;
    }
    ifstream ifs(argv[1]);
    if(!ifs){
        perror("open file failed\n");
        return -1;
    }
    map<string,int> msi;
    string word;
    while(ifs >> word)
        ++msi[word];
    ifs.close();
    foreach(msi,it){
        cout << it->first << " " << it->second << endl;
    }
    return 0;
}

此版本为第二个版本,不区分大小写,此版本主要是使用了map的第三个参数,使代码很简洁:

#include <iostream>
#include <fstream>
#include <map>
#include <cstring>
#ifndef foreach
#define foreach(container,it) \
    for(typeof((container).begin()) it = (container).begin();it != (container).end();++it)
#endif //foreach
using namespace std;
class Cmpstr{
public:
    bool operator()(const string& a,const string& b) const{
        return strcasecmp(a.c_str(),b.c_str()) < 0;
    }
};
int main(int argc,char* argv[])
{
    if(argc < 2){
        cerr << "usage" << argv[0] << "   filename " << endl;
        return -1;
    }
    ifstream ifs(argv[1]);
    if(!ifs){
        perror("open file failed\n");
        return -1;
    }
    map<string,int,Cmpstr> msi;
    string word;
    while(ifs >> word)
        ++msi[word];
    ifs.close();
    foreach(msi,it){
        cout << it->first << " " << it->second << endl;
    }
    return 0;
}

注:这里面有两个知识点,
1:map的第三个参数可以是仿函数,仿函数也就是比较器
2:c++实现比较器的方法如下:
如果为一个类定义了形如:
返回类型 operator()(形参表){}的操作符函数,那么这个类
所实例化的对象就可以被当做函数使用
#include <iostream>
using namespace std;
class Point  
{  
public:  
    Point() { _x = _y = 0; }  
    Point &operator()( int dx, int dy )  
        { _x += dx; _y += dy; return *this; }  
    friend ostream& operator<<(ostream& os,const Point& p){
        os << "x: " << p._x << " y: " << p._y << endl;
        return os;
    }
private:  
    int _x, _y;  
};  
 
int main()  
{  
   Point pt;  
   cout << pt( 3, 2 );  
}  

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值