Skip to Content
C++程序设计语言(第4部分:标准库)(原书第4版)
book

C++程序设计语言(第4部分:标准库)(原书第4版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
6h 57m
Chinese
Pearson
Content preview from C++程序设计语言(第4部分:标准库)(原书第4版)

32.2 算法

<algorithm>中定义了大约80个标准算法。它们操作由一对迭代器定义的(输入)序列(sequence)或单一迭代器定义的(输出)序列。当对两个序列进行拷贝、比较等操作时,第一个序列由一对迭代器[b:e)表示,但第二个序列只由一个迭代器b2表示,b2指出了序列的起始位置。我们要保证第二个序列包含足够多的元素供算法使用,例如,与第一个序列的元素一样多:[b2:b2+(e-b))。某些算法,例如sort(),要求随机访问迭代器;而很多算法,如find(),只顺序读取元素,因此只需前向迭代器即可正常工作。很多算法都遵循一种常规表示方式:返回序列的末尾来表示“未找到”(见4.5节)。我不再对每个算法都提及这一点。

无论是标准库算法还是用户自己设计的算法,都很重要:

·每个算法命名一个特定操作,描述其接口,并指定其语义。

·每个算法都可能广泛使用并被很多程序员熟知。

与函数和函数依赖关系定义不好的“随意代码”相比,算法的这两个特点可能带来正确性、可维护性以及性能上的巨大优势。如果你发现你写的一段代码有若干看起来没什么关联的循环、局部变量,或是有很复杂的控制结构,那么就应该考虑是否可以简化代码,将某些部分改写为具有描述性的名字以及良好定义的目的、接口和依赖关系的函数/算法。

STL风格的数值算法将在40.6节中介绍。

32.2.1 序列

标准库算法的理想目标是为可优化实现的某些东西提供最通用最灵活的接口。基于迭代器的接口是此理想目标的一个很好但不完美的近似(见33.1.1节)。例如,基于迭代器的接口无法直接表示序列的概念,从而导致在检测某些范围错误时可能会发生混淆情况:

通过为标准库算法提供容器版本,很多这类问题都可以得到缓解。例如:

这会简化user()的定义,使第二个错误不可能出现,而第一个错误会在运行时被捕获: ...

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

算法精讲视频课程:24篇系列讲座

算法精讲视频课程:24篇系列讲座

罗伯特·塞奇威克, 凯文·韦恩(Kevin Wayne)
可编程网络自动化

可编程网络自动化

Jason Edelman, Scott S. Lowe, Matt Oswalt
C语言核心技术(原书第2版)

C语言核心技术(原书第2版)

Peter Prinz, Tony Crawford
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉

Publisher Resources

ISBN: 9787111544395