c++primer课后题:实现文本查询(vector,map,set)
要求是查询文本中每一个单词的位置并打印出所在的行数以及整行的内容
这里的要求是使用到vector,map,set,作为联系。同时为了访问便利,也使用到了智能指针。
作为c的学习者开始学习c++,逐渐感觉到c++的强大与便利。
具体的许多内容、解释放在了代码的注释里面
上代码
#include <cstdio>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
using namespace std;
using std::string;
using std::vector;
struct TextQuery
{
shared_ptr<vector<string>> text_ptr = make_shared<vector<string>>();
//这里使用智能指针,是为了提升速度,减少拷贝的时间,如不使用,在主函数中调用需要拷贝整个vector
map<string, set<int>> m;
int place = 0;
TextQuery (ifstream &text_stream){
string words;
while (getline(text_stream,words) )
{
text_ptr->push_back(words);
}// 读取并初始化vector
for(auto i = text_ptr->begin();i!=text_ptr->end();i++)
{
place++;
istringstream str(*i);
string word;//这里是使用sstream来分割成单词,这种方法在c++primer中出现过许多次
while(str)
{
str>>word;
m[word].insert(place);
}
}//构造map和set两个部分
}
};
int main()
{
ifstream text_file("/Users/lxpig/Desktop/a.c");
TextQuery t(text_file);
string word;
cin>>word;
while(word != "#")
{
cout<<"there are "
<<t.m[word].size()
<<(t.m[word].size() > 1? " words" : " word")
<<endl;
for(auto i = t.m[word].begin();i != t.m[word].end(); i++)
{
cout<<"(it occurs at:"
<<*i
<<")==》";
cout<<*( t.text_ptr->begin()+(*i-1) )<<endl;
//这里仔细看一下就可以看懂的
//在这里是没有办法运用下标运算的(可能是我太菜不会吧)
}
cout<<"---------------------------------------昏哥线"<<endl;
cin>>word;
}
return 0;
}
文本如果是这些(歌曲:《Can't Take My Eyes Off You》)
You're just too good to be true
I can't take my eyes off you
You feel like heaven to touch
I wanna hold you so much
As long as love has arrived
And I thank God I'm alive
You're just too good to be true
I can't take my eyes off you
Pardon the way that I stare
There's nothing else to compare
The sight of you leaves me weak
There are no words left to speak
But if you feel like I feel
Please let me know if it's real
You're just too good to be true
I can't take my eyes off you
I love you baby
And if it's quite all right
I need you baby
To warm a lonely night
I love you baby
Trust in me when I say
Oh pretty baby
Don't bring me down I pray
Oh pretty baby
Now that I've found you this day
And let me love you baby
Let me love you
执行代码,输入:And
输出
there are 6 words
(it occurs at:6)==》And I thank God I'm alive
(it occurs at:18)==》And if it's quite all right
(it occurs at:27)==》And let me love you baby
(it occurs at:34)==》And I thank God I'm alive
(it occurs at:46)==》And if it's quite all right
(it occurs at:55)==》And let me love you baby
---------------------------------------昏哥线