- 1、本文档共9页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
C的一个简单的文本查询程序
本篇实例的目的是做一个简单的文本查询程序,通过编码过程有益于您对vector, map, set的基本掌握。
/*?*目的:一个简单的文本查询程序?*作用:程序将读取用户指定的任意文本文件,然后允许用户从该文件中查找单词。?*查询的结果是该单词出现的次数,并列出每次出现所在的行。?*如果某单词在同一行中多次出现,程序将只显示该行一次。?*行号按升序显示,即第 7 行应该在第 9 行之前输出,依此类推。?*/
/*思路:?*1.使用一个 vectorstring 类型的对象存储整个输入文件的副本。?*? 输入文件的每一行是该 vector 对象的一个元素。?*? 因而,在希望输出某一行时,只需以行号为下标获取该行所在的元素即可。?*2.将每个单词所在的行号存储在一个 set 容器对象中。?*? 使用 set 就可确保每行只有一个条目,而且行号将自动按升序排列。?*3.使用一个 map 容器将每个单词与一个 set 容器对象关联起来,?*? 该 set 容器对象记录此单词所在的行号。?*/
TextQuery.H文件
?
#ifndef TEXTQUERY_H#define TEXTQUERY_H#include string#include vector#include map#include set#include iostream#include fstream#include cctype#include cstring?class TextQuery {? ? // as beforepublic:? ? // typedef to make declarations easier? ? typedef std::string::size_type str_size;? ? typedef std::vectorstd::string::size_type line_no;?? ? /* interface:? ? *? ? read_file builds internal data structures for the given file? ? *? ? run_query finds the given?word?and returns set of lines on which it appears? ? *? ? text_line returns a requested line from the input file? ? */? ? void read_file(std::ifstream is)?? ? ? ? ? ? ? { store_file(is); build_map(); }? ? std::setline_no run_query(const std::string) const;?? ? std::string text_line(line_no) const;? ? str_size size() const { return lines_of_text.size(); }? ? void display_map();? ? ? ? // debugging aid: print the map?private:? ? // utility functions used by read_file? ? void store_file(std::ifstream); // store input file? ? void build_map(); // associated each word with a set of line numbers?? ? // remember the whole input file? ? std::vectorstd::string lines_of_text;??? ? // map word to set of the lines on which it occurs? ? std::map std::string, std::setline_no word_map;??? ? // characters that constitute whitespace? ? static std::string whitespace_chars;? ??? ? // canonicalizes text: removes punctuation and makes everything lower case? ? static std::string cleanup_str(const std::string);};#endif
?
T
文档评论(0)