利用set将输入到map中的字眼进行排除
set<string> exlusion = {"a", "an", "or", "the", "and", "but"}; //排除的字眼map<string, int> words; //被筛选的文本vector<string> out; //将筛选后的文本存入vector中string text;while (in_file >> text){if (exlusion.count(text)) //检测文本中的字眼在不在set中 {continue;}words[text]++; //以text为Key,0为Value的map被创建,value + 1out.push_back(text); //将筛选后的文本存储在vector中}
下面是从一个文本文件中,经过筛选,利用map进行单词出现次数的统计,set进行字眼的排除,并将筛选后的内容存入在一个vector中。最后利用迭代器进行内容的输出以及统计的结果。
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <algorithm>
//#include <functional> 其他的function object 如sort(it1, out.end(), lessthan(), greater<string>()); 使用greater-than进行排序而不是less-than
using namespace std;int main()
{//定义function objectclass lessthan {public:bool operator() (const string& s1, const string& s2) { return s1.size() < s2.size(); }};//打开输入文件ifstream in_file("in_file.txt");if (!in_file){cerr << "opps! can not find the file!" << endl;return -1;}set<string> exlusion = {"a", "an", "or", "the", "and", "but"}; //排除的文本map<string, int> words; //被筛选的文本vector<string> out; //将筛选后的文本存入vector中string text;while (in_file >> text){if (exlusion.count(text)){continue;}words[text]++;out.push_back(text);}vector<string>::iterator it1 = out.begin(); //打印筛选后的文本sort(it1, out.end()); //使用默认less-than进行排序,按照首字母排序stable_sort(it1, out.end(), lessthan()); //在保证按照首字母排序排序状态下,使用自定义的lessthan进行size排序for (it1; it1 != out.end(); it1++) //使用iterator进行遍历{cout << *it1 << " ";}cout << endl;map<string, int>::iterator it = words.begin(); //打印筛选后的文本以及其出现次数for (it; it != words.end(); it++) //使用iterator进行遍历{cout << it->first << ":\t" << it->second << "time(s)" << endl;}system("pause");return 0;
}
如果对文本文件中的内容进行无差别的输入,即不进行字眼的排除。可利用以下方法。iostream iterater的使用
istream_iterator<string> is(in_file); //in_file为文件地址的变量名 如ifstream in_file("in_file.txt");
istream_iterator<string> eof;vector<string> text;
copy(is, eof, back_inserter(text));ostream_iterator<string> os(cout, " "); //也可进行文件的输出ostream_iterator<string> os(out_file, " ");
copy(text.begin(), text.end(), os);