c++ prime+查询程序设计

TextQuery.h

#include <iostream>

#include <string>
#include <vector>
#include <set>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <map>
using namespace std;


class TextQuery{
     public:
  typedef vector<string>::size_type line_no;
void read_file(ifstream &is){
store_file(is);
build_map();
}
set<line_no> run_query(const string &) const;
string text_line(line_no) const;
private:
void store_file(ifstream &);
void build_map();
vector<string> lines_of_text;
map < string,set<line_no> > word_map;  //adding the space or error

};

TextQuery.cpp

#include "TextQuery.h"


void TextQuery::store_file(ifstream &is)
{
string textline;
while(getline(is,textline)){
lines_of_text.push_back(textline);
}
}


void TextQuery::build_map()
{
for(line_no line_num=0;line_num!=lines_of_text.size();++line_num)
{
istringstream line(lines_of_text[line_num]);
string word;
while(line>>word)
word_map[word].insert(line_num);
}
}


set<TextQuery::line_no> TextQuery::run_query(const string &query_word) const
{
map< string,set<line_no> >::const_iterator loc=word_map.find(query_word);
if(loc==word_map.end())
{
return set<line_no>();
}
else return loc->second;
}


string TextQuery::text_line(line_no line) const
{
if(line<lines_of_text.size())
return lines_of_text[line];
throw out_of_range("line number out of range");
}

main.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <map>
#include "TextQuery.h"
using namespace std;


void print_results(const set<TextQuery::line_no>& locs,const string & sought,const TextQuery & file)
{
typedef set<TextQuery::line_no> line_nums;
line_nums::size_type size=locs.size();
string s("time");
        //if(size==1)?s("time"):s("times");
cout<<"\n"<<sought<<"  occurs "<<size<<"  "<<s<<endl;
//make_plural(size,"time","s")<<endl;
line_nums::const_iterator it=locs.begin();
for(;it!=locs.end();++it)
{
cout<<"\t(line "
<<(*it)+1<<") "
<<file.text_line(*it)<<endl;
}

}
int main(int argc,char **argv)
{
ifstream infile(argv[1]);
if(argc<2||!infile){
cerr<<"no input file"<<endl;
return EXIT_FAILURE;
}
TextQuery tq;
tq.read_file(infile);
while(true){
cout<<"enter word, or q to quit"<<endl;
string s;
cin>>s;
if(!cin||s=="q")break;
set<TextQuery::line_no> locs=tq.run_query(s);
print_results(locs,s,tq);
}
return 0;
}


g++ -c main.cpp

g++ -o main TextQuery.o main.o

g++ -c TextQuery.cpp -o TextQuery.o

results:

the  occurs 8  time
(line 5)  golden on the table, 
(line 7) in the naval hospital 
(line 21)  on the deck; made a patient
(line 25) when the usual fever 
(line 26)  sank him in the dark. 
(line 28) the ribs' symmetrical fretwork(浮雕细工) , 
(line 29)  the pendant(垂饰) branches 
(line 30)  of phalanges, the serpentine(蜿蜒的) torc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值