Skip to Content
C++语言导学(原书第2版)
book

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

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

13.4.1 array

在<array>中定义的array表示一个尺寸固定的给定类型的元素的序列,其中元素数目在编译时指定。因此,array的元素可以分配在栈中、对象内或静态存储空间。元素分配空间所在的作用域就是定义array的作用域。理解array的最好方式是将其看作内置数组的一种特殊变形:尺寸固定、不会隐式地意外地转换成指针类型且提供了一些便捷的函数。与内置数组相比,使用array也没有(时间或空间上的)额外开销。array不遵循STL容器的“元素句柄”的模型,而是直接包含其元素。

我们可以用初始值列表初始化一个array:

其中,初始值列表中的元素数目必须小于等于为array指定的元素数目。

元素数目是必须指定的:

并且元素数目必须是一个常量表达式:

如果你希望元素数目可变,应该使用vector。

我们也可以在必要的时候将array显式传递给一个需要指针的C风格函数。例如:

既然vector灵活得多,我们为什么还要使用array呢?答案是array灵活性更低,但也因此更为简单。有时候,相比在自由存储中分配、通过vector(一种句柄)间接访问、然后还要释放掉元素,对栈中分配的元素直接进行访问会有显著的性能优势。但另一方面,栈是一种有限的资源(尤其是在嵌入式系统中),一旦发生栈溢出,后果不堪设想。 ...

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

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280