C++A Text-Query Program Design(文本查询程序设计)

前言

      本文内容是基于C++Primer 5th一个文本查询程序。中文版(参见12.3节,第430页),英文版($12.3 p.484)。

我为什么会选择记录这个文章?

      因为作者对这个程序进行了很全面的分析(至少我是这么认为),如何设计,如何优化、如何实现,都进行一番阐述。掌握这个类设计以及实现对初学者来说将是非常有用(我就是初学者哈)。

    本文不对代码细节讨论,只提供代码(细节可以参考书本),主要展现作者分析设计过程

问题引入:(一定要先思考,最好思路清晰了再往看




我的想法:

这个程序看上去,第一感觉就是对字符串操作,首先需要从文件读取字符串(文件操作),然后再进行查找,记录相关信息,似乎没什么难度。确实,我一开始是这么想的,但是真的写出代码还是有很多地方需要考虑,比如你从文件读取一行字符串,显然很简单,但是再从一行字符串里面分割单词呢??熟悉字符串流的同学可能就觉得没什么难度,确实,如果不清楚的话,或许就会对整个字符串逐个进行操作(显然很费时)。再之,如何确保当每行出现多个匹配单词的时候,确保不重复记录信息呢?? 再之,最后输出结果还是需要文件相关行的原始信息??等等。 

我的想法是保存一份从文件读取到的字符串的副本,需要查询的时候,再将查询单词跟这个副本中每个单词匹配,每一行字符串只要有一个满足就停止该行查询且保存这个行号(输出的时候该行号作为副本的下标索引),显然也能确保当一行有多个匹配单词出现,也只记录了对应行号一次。

我看了作者分析之后,受益匪浅。


看看作者的分析(非常重要):(注意划线部分,我认为非常值得借鉴的精华)


谨记:开始一个程序的设计的一种好方法是列出程序的操作。

分析完之后,接下来是组织这些操作了(数据结构),注意跟着作者的思路走。







当作者想使用一种更为抽象的方法解决这个问题的时候,又需要了新的问题,

当查找成功,查找函数的返回值是什么??如何设计才比较好?



通过前面的分析不难对这两个类进行实现了,接下来属于实现细节了,自己看代码,不难理解。  

可以参考下面代码


 类定义:ex12_27_30.h 

#ifndef CP5_ex12_27_h
#define CP5_ex12_27_h

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <memory>
using std::shared_ptr;

#include <iostream>
#include <fstream>
#include <map>
#include <set>

class QueryResult;
class TextQuery {
public:
    using LineNo = vector<string>::size_type;
    TextQuery(std::ifstream&);
    QueryResult query(const string&) const;

private:
    shared_ptr<vector<string>> input;
    std::map<string, shared_ptr<std::set<LineNo>>> result;
};

class QueryResult {
public:
    friend std::ostream& print(std::ostream&, const QueryResult&);

public:
    QueryResult(const string& s, shared_ptr<std::set<TextQuery::LineNo>> set,
                shared_ptr<vector<string>> v)
        : word(s), nos(set), input(v)
    {
    }

private:
    string word;
    shared_ptr<std::set<TextQuery::LineNo>> nos;
    shared_ptr<vector<string>> input;
};

std::ostream& print(std::ostream&, const QueryResult&);

#endif


类实现

#include "ex12_27_30.h"
#include <sstream>
#include <algorithm>
#include <iterator>

TextQuery::TextQuery(std::ifstream& ifs) : input(new vector<string>)
{
    LineNo lineNo{0};
    for (string line; std::getline(ifs, line); ++lineNo) {
        input->push_back(line);
        std::istringstream line_stream(line);
        for (string text, word; line_stream >> text; word.clear()) {
            // avoid read a word followed by punctuation(such as: word, )
            std::remove_copy_if(text.begin(), text.end(),
                                std::back_inserter(word), ispunct);
            // use reference avoid count of shared_ptr add.
            auto& nos = result[word];
            if (!nos) nos.reset(new std::set<LineNo>);
            nos->insert(lineNo);
        }
    }
}

QueryResult TextQuery::query(const string& str) const
{
    // use static just allocate once.
    static shared_ptr<std::set<LineNo>> nodate(new std::set<LineNo>);
    auto found = result.find(str);
    if (found == result.end())
        return QueryResult(str, nodate, input);
    else
        return QueryResult(str, found->second, input);
}

std::ostream& print(std::ostream& out, const QueryResult& qr)
{
    out << qr.word << " occurs " << qr.nos->size()
        << (qr.nos->size() > 1 ? " times" : " time") << std::endl;
    for (auto i : *qr.nos)
        out << "\t(line " << i + 1 << ") " << qr.input->at(i) << std::endl;
    return out;
}


测试

#include "ex12_27_30.h"
#include <iostream>

void runQueries(std::ifstream& infile)
{
    TextQuery tq(infile);
    while (true) {
        std::cout << "enter word to look for, or q to quit: ";
        string s;
        if (!(std::cin >> s) || s == "q") break;
        print(std::cout, tq.query(s)) << std::endl;
    }
}

int main()
{
    std::ifstream file("../data/storyDataFile.txt");
    runQueries(file);
}


这里也有另一个程序,关于shared_ptr和weak_ptr智能指针结合使用的一个实例,也是很不错的例子。

http://blog.csdn.net/qq_33850438/article/details/52955326


本文地址: http://blog.csdn.net/qq_33850438/article/details/52985035

参考:

C++ Primer 5th




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值