c++ TextQuery程序
TextQuery程序
我写的第一个版本
返回的是map
TextQuery.h
#inlucde
#include
TextQuery.cpp
include "TextQuery.h"
TextQuery::TextQuery(ifstream &is) {
string line;
istringstream iss;
string word;
size_t line_cnt = 0;
while(getline(is, line)) {
iss.clear();
iss.str(line);
text.push_back(line);
while(iss>>word) {
if(lut.fine(word) != lut.end()) {
lut[word].insert(line_cnt);
} else {
lut[owrd] = set{line_cnt};
}
}
++line_cnt;
}
}
map TextQuery::query(const string &str) {
map sh;
auto p = lut.find(str);
if((p != lut.end()) {
for(auto iter = p->second.begin(); iter != p->second.end(); ++iter) {
sh[*iter] = text[*text];
}
}
return sh;
}
这里用到了set
书上的版本
TextQuery.h
#pragma once
#include
#include
#include
TextQuery.cpp
#include "TextQuery.h"
TextQuery::TextQuery(ifstream &is) : text(make_shared>()) {
string line;
istringstream iss;
string word;
while (getline(is, line)) {
iss.clear();
iss.str(line);
text->push_back(line);
//cout << line << endl;
while (iss >> word) {
//cout << word << endl;
auto &lines = lut[word];
if (!lines) {
lines.reset(new set{ text->size() - 1 });
// lines = make_shared>();
// lines->insert(text-size() -1);
} else {
lines->insert(text->size() - 1);
}
}
}
}
QueryResult TextQuery::query(const string &str) const{
static shared_ptr> st_ptr(new set);
auto loc = lut.find(str);
if(loc != lut.end())
return QueryResult(str, text, loc->second);
else
return QueryResult(str, text, st_ptr);
}
void print(ostream &os, const QueryResult &pr) {
os << pr.sh << " occurs " << pr.lines->size() << " times"<begin(); iter != pr.lines->end(); ++iter) {
os << "(line " << *iter + 1 << ") " << (*pr.contents)[*iter] << endl;
}
}
测试代码
#include
#include
#include"TextQuery.h"
using namespace std;
int main() {
ifstream is("TextQuery.cpp");
TextQuery tq(is);
QueryResult qr = tq.query("QueryResult");
print(cout, qr);
return 1;
}
这个代码相比我写的代码的优点
- 使用指针返回查找的数据,返回的数据量比较小,没有大量拷贝。
- 为了使用指针使用了shared_ptr
- 在判断map中lut[word]这个数据是否存在是巧妙的使用了map在没有word对应键的元素的时候会插入这个键,值使用值初始化,shared_ptr值初始化就是nullptr,根据是否为nullptr来确定是否需要分配set的空间。