c++ primer 中的文本查询示例

2023-11-05

前言:

有个牛人叫bnu_chenshuo, 发微博说:

回复@TheRealBo: 学生编程练习:把 Unix 的命令行小工具用C/C++实现一遍:wc cat ls cp grep sort uniq nc head tail hexdump。把《C++ Primer》里的文本查询程序弄懂调通。写个大整数的加减乘运算。写个表达式计算器。把 string 和 vector<T> 自己实现一遍。写个太阳系几大星球的运动模拟程序。

好吧,一个一个来做吧。

今天第一个,c++ primer 中的文本查询示例。

该例子位于第10章节。(第15章节也有,引入了面向对象编程)

1.TextQuery.h

/*
 * TextQuery.h
 *
 *  Created on: 2011-8-26
 *      Author: gauss
 */

#ifndef TEXTQUERY_H_
#define TEXTQUERY_H_
#include <string>
#include <set>
#include <map>
#include <vector>
class TextQuery {
public:
	TextQuery();
	virtual ~TextQuery();
	typedef std::vector<std::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::set<line_no> run_query(const std::string&) const;
	std::string text_line(line_no) const;
	line_no size() const {
		return lines_of_text.size();
	}
	void print_results(const std::set<TextQuery::line_no>&, const std::string&, const TextQuery&);
private:
	// utility functions uesed 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::vector<std::string> lines_of_text;
	// map word to set of the lines on which it occurs
	std::map<std::string, std::set<line_no> > word_map;
	static std::string cleanup_str(const std::string&);
};
//void print_results(const std::set<TextQuery::line_no>&, const std::string&, const TextQuery&);
#endif /* TEXTQUERY_H_ */


2. TextQuery.cpp

/*
 * TextQuery.cpp
 *
 *  Created on: 2011-8-26
 *      Author: gauss
 */
#include "TextQuery.h"
#include <string>
#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <stdexcept>
#include <cctype>
using namespace std;
TextQuery::TextQuery() {
	// TODO Auto-generated constructor stub

}

TextQuery::~TextQuery() {
	// TODO Auto-generated destructor stub
}
void TextQuery::store_file(ifstream &is) {
	// read input file: store each line as element in lines_of_text
	string textline;
	while (getline(is, textline))
		lines_of_text.push_back(textline);
}

void TextQuery::build_map() {
	// process each line from the input vector
	for (line_no n = 0; n != lines_of_text.size(); ++n) {
		// we'll use line to read the text a word at a time
		istringstream line(lines_of_text[n]);
		string word;
		while (line >> word)
			// add this number to the set;
			// subscript will add word to the map if it's not already there
			word_map[cleanup_str(word)].insert(n);
	}
}

set<TextQuery::line_no> TextQuery::run_query(const string &query_word) const {
	// note: must use find and not subscript the map directly
	// to avoid adding words to word_map!
	map<string, set<line_no> >::const_iterator it = word_map.find(
			cleanup_str(query_word));
	if (it == word_map.end())
		return set<line_no> (); // not found, return empty set
	else
		return it->second;
}

string TextQuery::text_line(line_no line) const {
	if (line < lines_of_text.size())
		return lines_of_text[line];
	throw std::out_of_range("line number out of range");
}

string TextQuery::cleanup_str(const string &word) {
	string ret;
	for (string::const_iterator it = word.begin(); it != word.end(); ++it) {
		if (!ispunct(*it))
			ret += tolower(*it);
	}
	return ret;
}

//
void TextQuery::print_results(const set<TextQuery::line_no> &locs, const string &sought,
		const TextQuery &file) {
	// if the word was found, then print count and all occurrences
	typedef set<TextQuery::line_no> line_nums;
	line_nums::size_type size = locs.size();
	cout << "Executed Query for: " << sought << endl;
	cout << "match occurs " << size << " " << (size > 1 ? "times" : "time")
			<< endl;

	// print each line in which the word appeared
	line_nums::const_iterator it = locs.begin();
	for (; it != locs.end(); ++it) {
		cout << "(line "
		// don't confound user with text lines starting at 0
				<< (*it) + 1 << ") " << file.text_line(*it) << endl;
	}
}

主函数:

# include "TextQuery.h"
# include <iostream>
# include <fstream>
# include <string>
using namespace std;
int main(){
	TextQuery tq;
	ifstream fin("data.txt");
	tq.read_file(fin);
	while(true){
		cout << "enter the word to look fo,or q to exit: ";
		string s;
		cin >> s;
		if (s== "q") break;
		set<TextQuery::line_no> locs = tq.run_query(s);
		tq.print_results(locs,s,tq);
	}
}
data.txt摘自一段英文文章:

运行示意图:

enter the word to look fo,or q to exit: hurricane
Executed Query for: hurricane
match occurs 5 times
(line 1) With Hurricane Irene threatening a full-force hit, New York City on Thursday ordered the evacuation of nursing homes and senior centers in low-lying areas and made plans for the possible shutdown of the entire transit system.
(line 11) Mr. Bloomberg said the city was ordering nursing homes in those areas to evacuate residents beginning at 8 a.m. on Friday unless they receive special permission from state and city health officials, among them the city’s health commissioner, Dr. Thomas A. Farley, who, the mayor noted, was chairman of the community health sciences department at Tulane University when Hurricane Katrina hit New Orleans in 2005.
(line 19) The mayor said 300 street fairs over the weekend “would have to be curtailed” to keep streets clear for hurricane-related transportation — ambulances carrying patients to nursing homes or hospitals on higher ground, buses and city-owned trucks moving to where they would be ready for duty once the hurricane had swept by.
(line 23) The mayor cautioned that forecasts were not always accurate and that the hurricane, a sprawling storm still far away, could become weaker.
(line 27) That seemed to be the official mantra from South Jersey to coastal Connecticut on Thursday. In East Hampton, N.Y., crews removed sidewalk benches so they would not blow away if Hurric


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c++ primer 中的文本查询示例 的相关文章

  • Winform 没有.NET 框架?

    我必须创建一些表单并将其作为直接 EXE 提供 而不是安装程序 它安装 NET 框架 最终用户对此不满意 他们想要可以直接打开和工作的东西 我知道它可以作为网络完成 但我正在寻找 winforms 吗 请建议哪种工具 技术可以处理这个问题
  • 内存数据库不保存数据

    我有一个简单的网络应用程序 在客户端有 Angular 在服务器端有 ASP NET Core Web API 我使用内存数据库 services AddDbContext
  • 不会将字符串转换为十进制 C#(输入字符串的格式不正确。)

    Visual Studio 不会将我的字符串转换为十进制 错误 输入字符串的格式不正确 Code string test 123 95 decimal test1 decimal parse test string being an int
  • 使用 Azure AD B2C 登录 Xamarin Android 应用

    经过一周的研究可与 Azure AD B2C 一起使用 Xamarin 以 Android 平台 而不是 Xamarin Forms 为目标的身份验证原理后 我终于寻求一些建议 我有一个带有 登录 按钮的活动 我想通过按钮的触摸事件登录到
  • Cgo 生成的源无法在 MVC 上编译

    我有一个用 CGo 制作的共享库 它在 Linux 和 Android 上链接得很好 但是 当使用 Microsoft Visual Studio 2017 在 Windows 10 上进行编译时 出现以下错误 Microsoft R Pr
  • 移动构造函数和 std::move 混淆

    我正在阅读有关std move http en cppreference com w cpp utility move 移动构造函数和移动赋值运算符 说实话 我现在得到的只是困惑 现在我有一堂课 class A public int key
  • 无法从 ASP.NET 调用 DLL

    您好 我有一个 C Dll 它将与 cobol 应用程序交互 我们想通过互联网将数据发送到cobol 所以我创建了一个 C DLL 它将调用 C DLL 当我执行控制台应用程序时 它工作正常 但是当我尝试从 ASP NET 调用相同的 DL
  • asp.net-mvc 中模型绑定双精度的 CultureInfo 问题(2)

    在我的 Jquery 脚本中 我使用浏览器的 CultureInfo en UK 发布了两个双打 该浏览器使用 作为分数分隔符 我的 MVC 应用程序在区域设置为 nl BE 的服务器上运行 使用 作为分数分隔符 AcceptVerbs H
  • C# 在 Process.Kill() 期间仅完成了 ReadProcessMemory 或 WriteProcessMemory 请求的一部分

    我一直在广泛研究这个问题 但似乎找不到答案 我知道Only part of a ReadProcessMemory or WriteProcessMemory request was completed当 32 位进程尝试访问 64 位进程
  • 对 Dictionary 的键使用锁定

    我有一个Dictionary
  • 使用 TextBox 过滤 Datagridview 行

    我有一个绑定的 datagridView 我想使用 TextBox 值对其进行过滤 我使用了这段代码 private void ChercheStextBox TextChanged object sender EventArgs e tr
  • 在单独的线程上显示 WPF-“NotifyIcon”

    我目前正在开发一个 Office 加载项 我需要显示一个显示进度的通知对话框 我正在使用Philipp Sumi 的 wpf notifyicon http www codeproject com Articles 36468 WPF No
  • UTF8 vs. UTF16 vs. char* vs. 什么?谁来给我解释一下这个烂摊子!

    我已经设法忽略所有这些多字节字符的东西 但现在我需要做一些 UI 工作 我知道我在这方面的无知将会赶上我 谁能用几段或更少的内容解释我需要知道什么 以便我可以本地化我的应用程序 我应该使用什么类型 我同时使用 Net 和 C C 并且我需要
  • 如何使用 C# 从 Kafka 获取主题列表

    我想从卡夫卡获取主题列表 我正在使用 kafka net 客户端 但无法在有关获取主题列表的文档中找到 您可以使用 Confluence Kafka 包中提供的 AdminClient 列出所有主题 using Confluent Kafk
  • XNA:Unload() 的意义是什么?

    XNA 游戏有一个Unload 方法 其中内容应该被卸载 但这有什么意义呢 如果所有内容都被卸载 那么游戏一定会退出 在这种情况下 无论如何 所有内容都会被垃圾收集 对吗 据我了解 它对于任何标准用途都没有用 因为正如您所说 垃圾收集器为您
  • 在 C 中使用 fgets 和 strcmp [重复]

    这个问题在这里已经有答案了 我试图从用户那里获取字符串输入 然后根据他们输入的输入运行不同的函数 例如 假设我问 你最喜欢的水果是什么 我希望程序根据他们输入的内容进行评论 我不知道该怎么做 这是我到目前为止所拥有的 include
  • 哪个更好:保留向量容量、预分配大小或在循环中推回?

    我有一个函数 它将指向 char 数组和段大小的指针作为输入参数 并调用另一个需要std array
  • 将 CSS 类应用于 asp:Hyperlink 中的图像?

    我使用 asp Hyperlink 根据 URL 中的参数动态呈现链接图像 我需要能够将 CSS 类添加到渲染的 img 中 但不知道如何做到这一点 我知道我可以将 CssClass blah 添加到asp Hyperlink 但在渲染的H
  • 我的 QSqlQueryModel 不在列表视图中显示数据

    我正在玩 QSqlQueryModel 但我现在完全陷入困境 我一整天都在寻找解决方案 但到目前为止还没有运气 我所做的工作是它从我的 sqlite 数据库中提取数据 但由于某种原因我无法在列表视图中显示它 我的角色名似乎不存在 对于我从数
  • 向 Windows 服务发送 Windows 消息

    有没有任何工具可以将 WM ENDSESSION 等 Windows 消息发送 模仿 到 Windows 服务 OR 如何使用 C 向进程发送 Windows 消息 我只懂C 编辑 目的 基本上我必须调试 Windows 服务来修复仅在系统

随机推荐

  • learn more study less:如何高效学习

    博主狂言 几句有用的话 两个序 前言 如何使用本书 整体性学习策略 learn more study less 什么是整体性学习 结构 模型 熟悉的结构成熟结构 高速公路 整体性学习的顺序 获取阶段 理解阶段 拓展阶段 纠错阶段 应用阶段
  • 适用于嵌入式单片机的差分升级通用库+详细教程

    文章目录 1 什么是差分 增量升级 2 差分升级实现原理 3 关键点一 差分包制作过程 4 关键点二 嵌入式设备中差分算法库的移植 还原差分包 4 1 移植开关算法库代码 4 2 使用该库的流程 4 2 1 使用库的接口 4 2 2 接口使
  • cvui.h 使用总结

    很多情况下个人更多用QT搭配opencv进行一系列开发 QT可以迅速开发出合乎要求的界面 但是实际上 试验过程中并不需要一个美观且功能齐全的界面 使用opencv进行图像处理 可能反反复复使用的是按键 勾选按钮 图片显示 参数修改或者显示等
  • rk3588 与 rk3399 差异比较

    rk3588 与 rk3399 差异比较 在2016年中 瑞芯微 Rockchip 在深圳会展中心召开首届VR生态链对接峰会 正式发布 VR 旗舰级产品 RK3399 在2021年底 瑞芯微 Rockchip 在福州第六届开发者大会 正式发
  • gradle wapper时异常(task with that name already exists)

    场景 新服务发布到测试环境打包失败 原因 1 种子项目配置了gradle版本 导入本地的时候选择使用项目的gradle Use default gradle wrapper recommended 2 直接在terminal里面输入 gra
  • IntelliJ IDEA 2017.3.1 使用手册

    因为CSDN博客时不时会报错 后续更新在 https my oschina net datadev blog 2876471 目录 1 激活 首次设置 2 创建maven项目 3 执行maven命令 4 创建maven moudle工程 5
  • mmyolo训练yolov5~ppyoloe

    使用mmyolo检测工具箱 完成yolo系列算法的训练 包括环境的搭建及yolo系列算法的配置文件等 mmyolo官方地址 https github com open mmlab mmdeploy 相关文档 https github com
  • 干货满满【JVM监控及诊断工具-GUI篇】

    JVM监控及诊断工具 GUI篇 3 1 工具概述 使用上一章命令行工具或组合能帮您获取目标Java应用性能相关的基础信息 但它们存在下列局限 1 无法获取方法级别的分析数据 如方法间的调用关系 各方法的调用次数和调用时间等 这对定位应用性能
  • Recylerview(list,九宫格,瀑布流布局)

    package com example recyclerview import android support v7 app AppCompatActivity import android os Bundle import android
  • Java中类和对象的关系

    一 基本概念 1 类 类是一个模板 它描述一类对象的行为和状态 比如一张汽车设计图纸 2 对象 对象表示现实世界中一个具体的事物 对象是类的一个实例 有状态和行为 例如 一条狗是一个对象 它的状态有 颜色 名字 品种 行为有 摇尾巴 叫 吃
  • 闲来无事搭个代理池子

    基于ProxyPool创建Proxifier代理 如题目所见 闲来无事在做测试时发现被某网站封了IP 为防止再被封掉 因此有了这篇文章和搭建过程 0x01 安装redis服务 ubuntu16 04 apt get install redi
  • FISCO BCOS(十五)——— Windows下的go环境配置及beego环境配置并解决bee run报错问题

    1 下载地址 https golang google cn dl 2 双击打开下载的文件 一路按照默认点击下一步 安装位置可选 默认安装在c盘 3 go环境配置 很重要的 在系统变量名中新建变量名 GOPATH 变量值 E go space
  • React 合成事件

    文章借鉴 pingan8787 React合成事件 和 React合成事件官方文档 React 合成事件 一 概念介绍 React合成事件是React 模拟原生DOM事件所有能力 的一个事件对象 根据 W3C规范 来定义合成事件 兼容所有浏
  • UE4大数据可视化教程(21)——大屏云渲染通用像素流解决方案

    目录 项目打包前操作 复制信令服务器文件 快捷打开信令服务和启动项目 替换项目
  • 虚拟机中的Windows重置系统密码

    概述 相信大家不管是在企业还是个人都或多或少接触过虚拟机 在安装操作系统的时候 有的需要密码 而且默认有时总是提示需要更改密码 导致忘记密码 但又不能重装操作系统也不能回退就很烦 这里本博主今天突然想到这个问题就出一篇文章 虽然我没有忘记过
  • 软件工程基础知识复习宝典

    前言 此文档为个人大学时期应付期末考试时自行总结 用于理解并背诵相应的基本概念 一些计算和画图之类的内容需要结合书本例题进行复习 多做习题深刻掌握 中间大标题为老师给出的考纲中建议每一章需要掌握的一些知识点 如若需要doc文档版打印复习 请
  • [C++11]弱引用智能指针weak_ptr初始化和相关的操作函数

    弱引用智能指针 std weak ptr 可以看做是 shared ptr 的助手 它不管理 shared ptr 内部的指针 std weak ptr 没有重载操作符 和 gt 因为它不共享指针 不能操作资源 所以它的构造不会增加引用计数
  • 【YOLOv5】1.搭建Pycharm+Python+yolov5环境

    目录 一 安装Python 二 安装PyCharm 三 创建项目和虚拟环境 四 下载YOLOv5和依赖库 五 配置Pytorch 六 检验YOLOv5环境 一 安装Python 1 Python官方下载网址 Download Python
  • 解决echarts报错Cannot read properties of null (reading ‘getAttribute‘)

    前言 最近在写 echarts 的时候碰到了这么一个报错 如下图 造成报错的原因是因为 echarts 的图形容器还未生成就对其进行了初始化 下面几种方法是经本人自测最有效的解决方案 报错截图 解决方案 1 this nextTick 该方
  • c++ primer 中的文本查询示例

    前言 有个牛人叫bnu chenshuo 发微博说 回复 TheRealBo 学生编程练习 把 Unix 的命令行小工具用C C 实现一遍 wc cat ls cp grep sort uniq nc head tail hexdump 把