# Include <iostream>
# Include <fstream>
# Include <sstream>
# Include <string>
# Include <set>
# Include <map>
# Include <vector>
Using namespace: STD;
Class textquery
{
Public:
Typedef STD: vector <STD: String >:: size_type line_no;
Void read_file (STD: ifstream & file)
{
Store_file (File );
Build_map ();
}
STD: Set <line_no> run_query (const STD: string &) const;
STD: String text_line (line_no) const;
PRIVATE:
Void store_file (STD: ifstream &);
Void build_map ();
STD: vector <STD: String> text_of_line;
STD: Map <STD: String, STD: Set <line_no> word_map;
};
Void textquery: store_file (STD: ifstream & is)
{
String textline;
While (Getline (is, textline ))
Text_of_line.push_back (textline );
}
Void textquery: build_map ()
{
For (line_no linenum = 0; linenum! = Text_of_line.size (); ++ linenum)
{
Istringstream line (text_of_line [linenum]);
String word;
While (line> word)
Word_map [word]. insert (linenum );
}
}
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 <text_of_line.size ())
Return text_of_line [Line];
Else cerr <"out of range! "<Endl;
}
Void print_results (const set <textquery: line_no> & locs, const string sought, const textquery & TQ)
{
Typedef set <textquery: line_no> linenums;
Linenums: size_type size = locs. Size ();
Cout <"/N" <sought <"occurs" <size <"Times:" <Endl;
Linenums: iterator it = locs. Begin ();
For (; it! = Locs. End (); ++ it)
Cout <"/t (line" <(* It) + 1 <")" <TQ. text_line (* It) <Endl;
}
Int main ()
{
String fname ("D: // 1.txt ");
Ifstream file (fname. c_str ());
If (! File)
{
Cerr <"can not open file! "<Endl;
Return-1;
}
Textquery TQ;
TQ. read_file (File );
While (true)
{
Cout <"Please input the word to find out, 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 );
}
System ("pause ");
Return 0;
}