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版)

13.7.2 使用数组实现回文

当我们不能使用string(或vector),不得不使用数组存储字符时,该如何实现回文检测呢?让我们看看下面的程序:

为了测试is_palindrome(),我们首先需要将字符读入数组。为了实现这一操作,一种安全的(即没有数组溢出危险的)方法如下:

恰当地设置istream的宽度能避免下一个>>操作导致缓冲区溢出。不幸的是,这也意味着我们不知道读操作是遇见空白符结束的,还是缓冲区满结束的(因此还需要继续读入更多的字符)。另一方面,谁又能记得width()作用于输入流时的具体行为呢?标准库中string和vector更适合于作为输入缓冲区,因为它们能够根据输入的数据量动态调整大小。结尾0是必需的,因为对字符数组(C风格字符串)的大多数常用操作都假设字符串以0结束。借助read_word(),我们可以编写如下代码:

调用strlen(s)返回当调用read_word()结束之后数组中的字符数,cout<<s将输出数组中的字符,直至遇见字符0为止。

我们认为这种“数组方法”比“string方法”复杂得多,并且当我们尝试认真处理长字符串时,情况会变得更糟。参见习题10。 ...

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