最近在看C++ Primer复习C++的语法,看到书中15.9章中的文本查询示例时,觉得设计得非常不错,于是便动手照着实现了一个,修改了很久终于运行成功了,从中也学习到了很多的语法。下面把实现与总结分享给大家:
首先是在10.6.2节中实现的TextQuery类:
TextQuery.h
#ifndef __TestC____TextQuery__
#define __TestC____TextQuery__
#include <iostream>
#include <vector>
#include <set>
#include <map>
using namespace std;
class TextQuery {
public:
typedef vector<string>::size_type line_no;
TextQuery(string[], vector<string>::size_type);
set<line_no> run_query(const string&) const;
line_no size() const;
private:
vector<string> lines_of_text;
};
#endif /* defined(__TestC____TextQuery__) */
TextQuery.cpp
#include "TextQuery.h"
TextQuery::TextQuery(string strArray[], vector<string>::size_type count) {
lines_of_text.assign(strArray, strArray+count);
}
set<TextQuery::line_no> TextQuery::run_query(const string&word) const {
set<line_no> ret_lines;
for (int i=0;i<lines_of_text.size();i++) {
string line = lines_of_text[i];
if (line.find(word) != string::npos) {
ret_lines.insert(i);
}
}
return ret_lines;
}
TextQuery::line_no TextQuery::size() const {
return lines_of_text.size();
}
接下来是查询类的句柄类Query:
Query.h
#ifndef __TestC____Query__
#define __TestC____Query__
#include <iostream>
#include "TextQuery.h"
class Query_base;
class Query {
friend Query operator~(const Query &);
friend Query operator|(const Query &, const Query &);
friend Query operator&(const Query &, const Query &);
public:
Query