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 中的文本查询示例 的相关文章

  • 以文化中立的方式将字符串拆分为单词

    我提出了下面的方法 旨在将可变长度的文本拆分为单词数组 以进行进一步的全文索引处理 删除停止词 然后进行词干分析 结果似乎不错 但我想听听关于这种实现对于不同语言的文本的可靠性的意见 您会建议使用正则表达式来代替吗 请注意 我选择不使用 S
  • Web 客户端和 Expect100Continue

    使用 WebClient C NET 时设置 Expect100Continue 的最佳方法是什么 我有下面的代码 我仍然在标题中看到 100 continue 愚蠢的 apache 仍然抱怨 505 错误 string url http
  • 按成员序列化

    我已经实现了template
  • ASP.NET MVC:这个业务逻辑应该放在哪里?

    我正在开发我的第一个真正的 MVC 应用程序 并尝试遵循一般的 OOP 最佳实践 我正在将控制器中的一些简单业务逻辑重构到我的域模型中 我最近一直在阅读一些内容 很明显我应该将逻辑放在域模型实体类中的某个位置 以避免出现 贫血域模型 反模式
  • BitTorrent 追踪器宣布问题

    我花了一点业余时间编写 BitTorrent 客户端 主要是出于好奇 但部分是出于提高我的 C 技能的愿望 我一直在使用理论维基 http wiki theory org BitTorrentSpecification作为我的向导 我已经建
  • 在 ASP.NET 5 中使用 DI 调用构造函数时解决依赖关系

    Web 上似乎充斥着如何在 ASP NET 5 中使用 DI 的示例 但没有一个示例显示如何调用构造函数并解决依赖关系 以下只是众多案例之一 http social technet microsoft com wiki contents a
  • Javascript split 不是一个函数

    嘿朋友们 我正在使用 javascript sdk 通过 jQuery facebook 多朋友选择器在用户朋友墙上发布信息 但是我收到此错误friendId split 不是函数 这是我的代码 function recommendToFr
  • C#中如何移动PictureBox?

    我已经使用此代码来移动图片框pictureBox MouseMove event pictureBox Location new System Drawing Point e Location 但是当我尝试执行时 图片框闪烁并且无法识别确切
  • 使用 Bearer Token 访问 IdentityServer4 上受保护的 API

    我试图寻找此问题的解决方案 但尚未找到正确的搜索文本 我的问题是 如何配置我的 IdentityServer 以便它也可以接受 授权带有 BearerTokens 的 Api 请求 我已经配置并运行了 IdentityServer4 我还在
  • 仅将 char[] 的一部分复制到 String 中

    我有一个数组 char ch 我的问题如下 如何将 ch 2 到 ch 7 的值合并到字符串中 我想在不循环 char 数组的情况下实现这一点 有什么建议么 感谢您花时间回答我的问题 Use new String value offset
  • 这些作业之间是否存在顺序点?

    以下代码中的两个赋值之间是否存在序列点 f f x 1 1 x 2 不 没有 在这种情况下 标准确实是含糊不清的 如果你想确认这一点 gcc 有这个非常酷的选项 Wsequence point在这种情况下 它会警告您该操作可能未定义
  • 覆盖子类中的字段或属性

    我有一个抽象基类 我想声明一个字段或属性 该字段或属性在从该父类继承的每个类中具有不同的值 我想在基类中定义它 以便我可以在基类方法中引用它 例如覆盖 ToString 来表示 此对象的类型为 property field 我有三种方法可以
  • WPF/C# 将自定义对象列表数据绑定到列表框?

    我在将自定义对象列表的数据绑定到ListBox in WPF 这是自定义对象 public class FileItem public string Name get set public string Path get set 这是列表
  • 向现有 TCP 和 UDP 代码添加 SSL 支持?

    这是我的问题 现在我有一个 Linux 服务器应用程序 使用 C gcc 编写 它与 Windows C 客户端应用程序 Visual Studio 9 Qt 4 5 进行通信 是什么very在不完全破坏现有协议的情况下向双方添加 SSL
  • 为什么编译时浮点计算可能不会得到与运行时计算相同的结果?

    In the speaker mentioned Compile time floating point calculations might not have the same results as runtime calculation
  • 基于 OpenCV 边缘的物体检测 C++

    我有一个应用程序 我必须检测场景中某些项目的存在 这些项目可以旋转并稍微缩放 更大或更小 我尝试过使用关键点检测器 但它们不够快且不够准确 因此 我决定首先使用 Canny 或更快的边缘检测算法 检测模板和搜索区域中的边缘 然后匹配边缘以查
  • IEnumreable 动态和 lambda

    我想在 a 上使用 lambda 表达式IEnumerable
  • 如何将服务器服务连接到 Dynamics Online

    我正在修改内部管理应用程序以连接到我们的在线托管 Dynamics 2016 实例 根据一些在线教程 我一直在使用OrganizationServiceProxy out of Microsoft Xrm Sdk Client来自 SDK
  • 如何在文本框中插入图像

    有没有办法在文本框中插入图像 我正在开发一个聊天应用程序 我想用图标图像更改值 等 但我找不到如何在文本框中插入图像 Thanks 如果您使用 RichTextBox 进行聊天 请查看Paste http msdn microsoft co
  • 使用.NET技术录制屏幕视频[关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 有没有一种方法可以使用 NET 技术来录制屏幕 无论是桌面还是窗口 我的目标是免费的 我喜欢小型 低

随机推荐

  • 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 把