C++ Primer 5th筆記(chap 12)動態記憶體 TextQuery
阿新 • • 發佈:2021-02-14
技術標籤:c++ primer筆記
textQuery.h
class QueryResult; // declaration needed for return type in the query function
class TextQuery {
public:
#ifdef TYPE_ALIAS_DECLS
using line_no = std::vector<std::string>::size_type;
#else
typedef std::vector<std::string>::size_type line_no;
#endif
TextQuery (std::ifstream&);
QueryResult query(const std::string&) const;
void display_map(); // debugging aid: print the map
private:
std::shared_ptr<std::vector<std::string>> file; // input file
// maps each word to the set of the lines in which that word appears
std:: map<std::string, std::shared_ptr<std::set<line_no>>> wm;
// canonicalizes text: removes punctuation and makes everything lower case
static std::string cleanup_str(const std::string&);
};
queryResult.h
class QueryResult {
friend std::ostream& print(std::ostream&, const QueryResult&);
public:
typedef std::vector<std::string>::size_type line_no;
typedef std::set<line_no>::const_iterator line_it;
QueryResult(std::string s,
std::shared_ptr<std::set<line_no>> p,
std::shared_ptr<std::vector<std::string>> f):
sought(s), lines(p), file(f) { }
std::set<line_no>::size_type size() const { return lines->size(); }
line_it begin() const { return lines->cbegin(); }
line_it end() const { return lines->cend(); }
std::shared_ptr<std::vector<std::string>> get_file() { return file; }
private:
std::string sought; // word this query represents
std::shared_ptr<std::set<line_no>> lines; // lines it's on
std::shared_ptr<std::vector<std::string>> file; //input file
};
std::ostream &print(std::ostream&, const QueryResult&);
void test(){
// open the file from which user will query words
ifstream infile;
infile.open("E:/temp/queryText");
// infile is an ifstream that is the file we want to query
TextQuery tq(infile); // store the file and build the query map
// iterate with the user: prompt for a word to find and print results
while (true) {
cout << "enter word to look for, or q to quit: ";
// stop if we hit end-of-file on the input or if a 'q' is entered
string s;
if (!(cin >> s) || s == "q")
break;
// run the query and print the results
print(cout, tq.query(s)) << endl;
}
}
queryText file:
Some programs read cin for their input.
Sample data files are in the data directory:
File Programs that use that input file
---- --------
storyDatafile usealloc
storyDatafile querymain
Alice querymain
alloc allocPtr
alloc allocSP
Programs not listed above print output and do
not read any input
result: