題目描述:請(qǐng)編寫程序,從包含大量單詞的文本中刪除出現(xiàn)次數(shù)最少的單詞。如果有多個(gè)單詞都出現(xiàn)最少的次數(shù),則將這些單詞都刪除。 輸入數(shù)據(jù):程序讀入已被命名為corpus.txt的一個(gè)大數(shù)據(jù)量的文本文件,該文件包含英文單詞和中文單詞,詞與詞之間以一個(gè)或多個(gè)whitespace(制表符、空格符和換行符一般被統(tǒng)稱為“白字符”(whitespace characters))分隔。(為便于調(diào)試,您可下載測(cè)試corpus.txt文件,實(shí)際運(yùn)行時(shí)我們會(huì)使用不同內(nèi)容的輸入文件。) 輸出數(shù)據(jù):在標(biāo)準(zhǔn)輸出上打印刪除了corpus.txt中出現(xiàn)次數(shù)最少的單詞之后的文本(詞與詞保持原來的順序,仍以空格分隔)。
評(píng)分標(biāo)準(zhǔn):
程序輸出結(jié)果必須正確,內(nèi)存使用越少越好,程序的執(zhí)行時(shí)間越快越好
#include<iostream>
#include<fstream>
#include<map>
#include<vector>
#include<string>
#include<cstring>
#include<cstdlib>
#include<iterator>
#include<algorithm>
#include<cctype>
using namespace std;
typedef map<string,int>::iterator mit;
typedef string::size_type sit;
int main()
{
map<string,int> words_count;
vector<string> sve;
string word;
string s=",!?.:""\n;'";
ifstream fin("E:\\corpus.txt");
if(!fin)
{
cerr<<"unable to open file"<<endl;
exit(0);
}
//讀取并統(tǒng)計(jì)單詞單詞
while(fin>>word)
{
sit iter=word.find_first_of(s);
if(iter!=string::npos)
word=word.substr(0,iter-0); //處理標(biāo)點(diǎn)符號(hào)
string temp(strlwr(const_cast<char*>(word.c_str())));
word=temp;
sve.push_back(word);
++words_count[word];
}
fin.close();
//刪除個(gè)數(shù)最少的單詞
mit i=words_count.begin();
int n=i->second;
for(;i!=words_count.end();++i)
if(i->second<n) n=i->second;
for(mit i=words_count.begin();i!=words_count.end(); )
{
if(i->second==n)
{
sve.erase(remove(sve.begin(),sve.end(),i->first),sve.end());
++i;
}
else ++i;
}
//輸出到屏幕
copy(sve.begin(),sve.end(),ostream_iterator<string>(cout," "));
cout<<endl;
system("pause");
return 0;
}