从来就没有救世主  也不靠神仙皇帝  要创造人类的幸福  全靠我们自己  

面试笔试题

 

1.  文本文件里面有很多单词(单词与单词之间以空格、换行符隔开,且不管单个单词的正确性),统计各单词出现的次数,删掉出现次数最少的那些

  实现:fstream读入事先准备好的文件test.txt,存到C++的关联容器map,用单词string做key,出现的次数int做value,找到最小的value,然后回写到testout.txt

map<string,int> word_count;
fstream rwfile;
string str;
int min = 0;
rwfile.open("E:/code/C++/TestCPlus/test.txt",ios_base::in);
if(!rwfile) {
     cout<<"open file error\n";
     return;
}
while(rwfile>>str) {
    word_count[str] ++;
    int count = word_count[str];
    if(min == 0) {
        min = word_count[str];
    }
    if(min>count) {
        min = count;
    }
}
//文件中所有单词和次数都存到map里面了,且找到了最小次数
rwfile.close();
rwfile.open("E:/code/C++/TestCPlus/testout.txt",ios::out | ios::trunc);
map<string,int>::iterator iter = word_count.begin();
while(iter != word_count.end()) {
    if(iter->second != min) {
        rwfile<<iter->first<<"  ";
    }
    ++iter;
}
rwfile.close();

 

posted @ 2020-03-23 02:12  T,X  阅读(120)  评论(0编辑  收藏  举报