练习3.1 写一个读取文本文件的程序,将文件中的每个单词存入map。map的key便是刚才所说的单词,map的value则是该单词在文本文件中出现的次数。再定义一份由“排除单词”组成的set,其中包含诸如 a,an,the,but,and,or之类的单词。在将某单词置入map之前,先确定该单词并不在“排除字集”中,一旦文本文件读取完毕,请显示一份单词列表,并显示各个单词的出现次数。你可以在显示单词之前,允许用户查询某个单词是否出现于文本文件中。
#ifndef PRINT_H_INCLUDED
#define PRINT_H_INCLUDED
#include <vector>
#include <map>
#define PRINT_VECTOR(T) void print_container(vector<T> t) { \
vector<T>::iterator it = t.begin(); \
for(; it != t.end(); it++) { \
std::cout << *it << std::endl; \
} \
std::cout << "\n"; }
#define PRINT_MAP(K,V) void print_container(map<K,V> m) { \
map<K,V>::iterator it = m.begin(); \
for(; it != m.end(); it++) {\
std::cout << "key : " << it->first << " value : " << it->second << std::endl; \
} }
#endif // PRINT_H_INCLUDED
为了方便我这里先定义好了打印的宏。在头文件print.h中
下面是一个初略的实现,
#include "print.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <set>
using namespace std;
//用头文件的宏来定义打印函数。
PRINT_MAP(string,int)
PRINT_VECTOR(string)
const string arr[6] = {"a","an","and","but","or","the"};
const set<string> g_exclusion(arr,arr+6);
void input() {
cout << "input your file name : ";
string file_name;
cin >> file_name;
ifstream infile(file_name.c_str(),ifstream::in);
if(!infile) {
cerr << "can not find the file ";
exit(1);
}
istream_iterator<string> is(infile);
istream_iterator<string> eof;
vector<string> content;
map<string,int> mymap;
copy(is,eof,back_inserter(content)); //把文本文件的内容插入到vector中
for(vector<string>::iterator it = content.begin();
it != content.end(); ++it) {
if(g_exclusion.count(*it) == 0) //不包含在排除字集中,加入到map中
mymap[*it]++;
}
cout << " input you want to search word : ";
string word;
cin >> word;
if(!mymap.count(word)) {
cout << " sorry ,doesn't find the word : " << word <<endl;
} else {
cout << "yes the map contain the word : " << word << endl;
}
cout << "the file's content is : " << endl;
print_container(content);
cout << "word count-------------------------" << endl;
print_container(mymap);
}
int main() {
input();
}
输出结果: