这个版本为区分大小写的实现(代码可直接通过编译):
#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 );
}