您的位置:首页 > 编程语言 > C语言/C++

编程题目记录140522:C++的第一份还算丰富的代码

2014-05-23 11:09 495 查看
题目:

  C++ primer第十章的大作业,打开一个文件,输入一个字符串,查找该字符串出现的所有地方并列出

计划:

  TestQuery类。尝试通过multimap来替代原书中map 和set的功能

class TestQuery
{
public:
void InputFile(ifstream *fptr)
{
StoreLines(fptr);
WordCount();
}
void StoreLines(ifstream *fptr);
void WordCount();
void Quest(string word);
private:
vector<string> lines;
multimap<string,int> word_cnts;
};


代码:

int main()
{
ifstream fp("textof10.txt");
if(fp==NULL)
cerr<<"open file error!"<<endl;

TestQuery tq;
tq.InputFile(&fp);

string word;
cout<<"Please enter the word you want to search,q to quit"<<endl;

while(cin>>word&&word!="q")
tq.Quest(word);

return 0;
}

void TestQuery::StoreLines(ifstream *fptr)
{
string line;
while(getline(*fptr,line))
lines.push_back(line);
}

void TestQuery::WordCount()
{
for(vector<string>::size_type i=0;i<=lines.size()-1;++i)
{
istringstream line_by_word(lines[i]);
string word;
while(line_by_word>>word)
word_cnts.insert(make_pair(word,i));
}
}

void TestQuery::Quest(string word)
{
multimap<string,int>::size_type tol=word_cnts.count(word);
cout<<word<<" occurs "<<tol<<" times."<<endl;
multimap<string,int>::iterator itl=word_cnts.lower_bound(word);
multimap<string,int>::iterator itu=word_cnts.upper_bound(word);

for(;itl!=itu;++itl)
cout<<"\t(line "<<itl->second+1<<") "<<lines[itl->second]<<endl;
}


补充:

  目前有两处“bug”:1、并没有按照书中那样去修改单词只出现一次时候“time”一词的单双数显示。2、统计单词使用了istringstream,该类型通过空格来区分单词,即无法统计字符串真正出现过的所有地方。

心得:

  总算是顺利的沿着C++的风格跑了一遍,练手而已……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐