Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

10.11.3 改变表示方法

为了使Month的>>能正常工作,我们需要提供一个方法,来读入月份的符号表示。相似地,我们将用符号表示提供匹配的写。一种冗长的表示方法是使用if语句:

这种方法不仅冗长,而且将月份名固化到了程序中。更好的方法是将月份名存入一个表中,使得即便不得不改变符号表示时,也无须改动主程序。我们决定用一个vector<string>来描述月份的符号表示,另外设计一个初始化函数和一个查找函数。

为了避免疑惑,C++标准库提供了一种简单的方法来完成相同的工作,参见16.6.1节中map<string.int>的相关内容。

当需要进行输出时,我们将面临一个逆问题。我们在内存中用一个整数表示月份,但输出时希望用符号表示形式。解决方案与输入基本相似,只是把string到int的映射表变为int到string的映射表:

好了,你是否真正阅读了全部代码和注释了呢?还是眼睛一眨就跳到末尾了?谨记学习编写高质量代码的最好途径就是阅读大量代码。不管你信不信,本例中我们使用的方法虽很简单,但在没有帮助的情况下领悟其精髓并不容易。读取数据是很基本的,正确编写输入循环(正确初始化用到的变量)是很基本的,转换表示方式也很基本。也就是说,你应该学会这些。唯一的问题是,你是否能学会很好地使用这些技术,以及是否在熬夜之前学会这些基本的技术。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252