C++|内置数组、STL array、STL vector
xsobi 2024-11-24 00:29 19 浏览
T[N]
Built-in array: a fixed-size contiguously allocated sequence of N elements of type T; implicitly converts to a T*
内置数组:固定大小的连续分配的T型N个元素序列;隐式转换为T*
array<T,N>
A fixed-size contiguously allocated sequence of N elements of type T; like the built-in array, but with most problems solved
T型N个元素的固定大小连续分配序列;与内置数组类似,但大多数问题都已解决
A vector is a sequence of elements of a given type. The elements are stored contiguously in memory. A typical implementation of vector will consist of a handle holding pointers to the first element, one-past-the-last element, and one-past-the-last allocated space (§13.1) (or the equivalent information represented as a pointer plus offsets):
vector是给定类型的元素序列。元素连续存储在存储器中。vector的典型实现将由一个句柄组成,该句柄持有指向第一个元素的指针,一个指针位于最后一个元素之后,一个位于最后分配的空间之后(或表示为指针加偏移的等效信息):
In addition, it holds an allocator (here, alloc), from which the vector can acquire memory for its elements. The default allocator uses new and delete to acquire and release memory. Using a slightly advanced implementation technique, we can avoid storing any data for simple allocators in a vector object.
此外,它还包含一个分配器(这里是alloc),vector可以从中获取元素的内存。默认分配器使用new和delete来获取和释放内存。使用稍微先进的实现技术,我们可以避免在vector对象中存储简单分配器的任何数据。
template<typename T>
class Vector {
allocator<T> alloc; // standard-library allocator of space for Ts
T* elem; // pointer to first element
T* space; // pointer to first unused (and uninitialized) slot
T* last; // pointer to last slot
public:
// ...
int size() const { return space-elem; } // number of elements
int capacity() const { return last-elem; } // number of slots available for elements
// ...
void reserve(int newsz); // increase capacity() to newsz
// ...
void push_back(const T& t); // copy t into Vector
void push_back(T&& t); // move t into Vector
};
STL array, and tuple elements are contiguously allocated; list and map are linked structures.
StL array和tuple元素被连续分配;list和map是链接结构。
An STL array, defined in <array>, is a fixed-size sequence of elements of a given type where the number of elements is specified at compile time. Thus, an array can be allocated with its elements on the stack, in an object, or in static storage. The elements are allocated in the scope where the array is defined. An array is best understood as a built-in array with its size firmly attached, without implicit, potentially surprising conversions to pointer types, and with a few convenience functions provided. There is no overhead (time or space) involved in using an array compared to using a built-in array.
在<array>中定义的STL array是给定类型的元素的固定大小序列,其中元素的数量在编译时指定。因此,可以在堆栈、对象或静态存储中为数组分配元素。元素在定义数组的范围内分配。STL array最好理解为一个内置数组(built-in array),其大小固定,没有隐含的、可能令人惊讶的指针类型转换,并且提供了一些方便的函数。与使用内置数组相比,使用STL array不需要任何开销(时间或空间)。
An array does not follow the “handle to elements” model of STL containers. Instead, an array directly contains its elements. It is nothing more or less than a safer version of a built-in array.
STL array不遵循STL容器的“句柄到元素”模型。相反,数组直接包含其元素。它或多或少是内置array的一个更安全的版本。
This implies that an array can and must be initialized by an initializer list:
这意味着数组可以也必须由初始值设定项列表初始化:
array<int,3> a1 = {1,2,3};
The number of elements in the initializer must be equal to or less than the number of elements specified for the array.
初始值设定项中的元素数必须等于或小于为数组指定的元素数。
The element count is not optional, the element count must be a constant expression, the number of elements must be positive, and the element type must be explicitly stated:
元素计数不是可选的,元素计数必须是常量表达式,元素数必须为正数,并且必须明确声明元素类型:
void f(int n)
{
array<int> a0 = {1,2,3}; // error size not specified
array<string,n> a1 = {"John's", "Queens' "}; // error: size not a constant expression
array<string,0> a2; // error: size must be positive
array<2> a3 = {"John's", "Queens' "}; // error: element type not stated
// ...
}
If you need the element count to be a variable, use vector.
如果您需要元素计数为变量,请使用vector。
When necessary, an STL array can be explicitly passed to a C-style function that expects a pointer. For example:
必要时,可以将STL array显式传递给需要指针的C样式函数。例如:
void f(int* p, int sz); // C-style interface
void g()
{
array<int,10> a;
f(a,a.size()); // error: no conversion
f(a.data(),a.size()); // C-style use
auto p = find(a,777); // C++/STL-style use (a range is passed)
// ...
}
Why would we use an STL array when vector is so much more flexible? An array is less flexible so it is simpler. Occasionally, there is a significant performance advantage to be had by directly accessing elements allocated on the stack rather than allocating elements on the free store, accessing them indirectly through the vector (a handle), and then deallocating them. On the other hand, the stack is a limited resource (especially on some embedded systems), and stack overflow is nasty. Also, there are application areas, such as safety-critical real-time control, where free store allocation is banned. For example, use of delete may lead to fragmentation or memory exhaustion.
当STL vector如此灵活时,我们为什么要使用STL array?STL array不太灵活,因此更简单。有时,直接访问堆栈上分配的元素,而不是在空闲存储(堆)上分配元素,通过vector(句柄)间接访问它们,然后释放它们,会带来显著的性能优势。另一方面,堆栈是一种有限的资源(尤其是在一些嵌入式系统上),并且堆栈溢出非常严重。此外,还有一些应用领域,如安全关键型实时控制,禁止空闲存储(堆)分配。例如,使用delete可能会导致碎片化或内存耗尽。
Why would we use an STL array when we could use a built-in array? An array knows its size, so it is easy to use with standard-library algorithms, and it can be copied using =. For example:
当我们可以使用内置数组时,为什么要使用STL array?STL array知道它的大小,因此它很容易与标准库算法一起使用,并且可以使用操作符“=”复制它。例如:
array<int,3> a1 = {1, 2, 3 };
auto a2 = a1; // copy
a2[1] = 5;
a1 = a2; // assign
However, the main reason to prefer STL array is that it saves me from surprising and nasty conversions to pointers. Consider an example involving a class hierarchy:
然而,更喜欢数组的主要原因是,它避免了对指针的令人惊讶和讨厌的转换。考虑一个涉及类层次结构的示例:
void h()
{
Circle a1[10];
array<Circle,10> a2;
// ...
Shape* p1 = a1; // OK: disaster waiting to happen
Shape* p2 = a2; // error: no conversion of array<Circle,10> to Shape* (Good!)
p1[3].draw(); // disaster
}
The “disaster” comment assumes that sizeof(Shape)<sizeof(Circle), so subscripting a Circle[] through a Shape* gives a wrong offset. All standard containers provide this advantage over built-in arrays.
“disaster”注释假定sizeof(Shape)<size of(Circle),因此通过Shape*下标Circle[]给出了错误的偏移量。与内置数组相比,所有标准容器都提供了这一优势。
ref
Bjarne Stroustrup, A Tour of C++ Third Edition
-End-
相关推荐
- 大模型技术:详解LangGraph,从基础到高级
-
图片来自DALL-E3LangChain是构建由Lardge语言模型提供支持的应用程序的领先框架之一。借助LangChain表达语言(LCEL),定义和执行分步操作序列(也称为链)变得更加简...
- SQL知识大全三):SQL中的字符串处理和条件查询
-
点击上方蓝字关注我们今天是SQL系列的第三讲,我们会讲解条件查询,文本处理,百分比,行数限制,格式化以及子查询。条件查询IF条件查询#if的语法IF(expr1,expr2,expr3)#示例S...
- 聊聊Spring AI Alibaba的PdfTablesParser
-
序本文主要研究一下SpringAIAlibaba的PdfTablesParserPdfTablesParsercommunity/document-parsers/spring-ai-alibab...
- SpringBoot数据库管理 - 用Liquibase对数据库管理和迁移?
-
Liquibase是一个用于用于跟踪、管理和应用数据库变化的开源工具,通过日志文件(changelog)的形式记录数据库的变更(changeset),然后执行日志文件中的修改,将数据库更新或回滚(ro...
- MySQL合集-单机容器化
-
MySQL单机容器化mkdir-p/opt/mysql/{data,etc}cpmy.cnf/opt/mysql/etc#dockersearchmysqldockerpullm...
- 差异基因分析不会做?最简单的火山图做法,一秒学会
-
最近很多刚了解生信的同学问喵学姐:看了一些文献,文献里的各种图怎么看呀,完全看不懂。今天喵学姐就来给大家讲一讲我们平时做的最基础的差异分析——火山图火山图(Volcanoplot)是散点图的一种,它...
- 每分钟写入6亿条数据,携程监控系统Dashboard存储升级实践
-
一、背景概述框架Dashboard是一款携程内部历史悠久的自研监控产品,其定位是企业级Metrics监控场景,主要提供用户自定义Metrics接入,并基于此提供实时数据分析和视图展现的面板服务,提供...
- 高效开发库:C++ POCO库开发者使用指南
-
目录POCO库简介POCO库的特点POCO库的模块分类POCO库的应用场景各模块功能详解与代码示例1.POCO库简介POCO(PortableComponents)是一个开源的C++类库,旨在为开...
- Oracle中JDBC处理PreparedStatement处理Char问题浅析
-
最近碰到一个奇怪的问题,同样的Java代码,在不同的数据库执行,结果集却不同?代码片段如下:表的定义:SAMPLE_TABLE(IDINTEGER,NAMECH...
- mp4封装格式各box类型讲解及IBP帧计算
-
mp4封装格式各box类型讲解及IBP帧计算目录;总结送学习大纲零基础到实战boxftypboxmoovboxmvhdbox(MovieHeaderBox)trakbox(Track...
- 「猪译馆」ASFV在不同基质中的存活时间(一)
-
作者Author欧洲食品安全署EuropeanFoodSafetyAuthority(EFSA),AndreaGervelmeyer欧盟委员会委托欧洲食品安全署对非洲猪瘟病毒在不同基质中...
- 视频封装格式:MP4格式详解
-
1.MP4格式概述1.1简介MP4或称MPEG-4第14部分(MPEG-4Part14)是一种标准的数字多媒体容器格式。扩展名为.mp4。虽然被官方标准定义的唯一扩展名是.mp4,但第三方通...
- 音视频八股文(10)-- mp4结构
-
介绍mp4文件格式又被称为MPEG-4Part14,出自MPEG-4标准第14部分。它是一种多媒体格式容器,广泛用于包装视频和音频数据流、海报、字幕和元数据等。(顺便一提,目前流行的视频编码格式...
- 大数据ClickHouse进阶(九):ClickHouse的From和Sample子句
-
#头条创作挑战赛#ClickHouse的From和Sample子句一、From子句From子句表示从何处读取数据,支持2种形式,由于From比较简单,这里不再举例,2种使用方式如下:SELECTcl...
- 一文读懂MP4封装格式
-
简介MP4或称MPEG-4第14部分(MPEG-4Part14)是一种标准的数字多媒体容器格式。扩展名为.mp4。虽然被官方标准定义的唯一扩展名是.mp4,但第三方通常会使用各种扩展名来指示文件的...
- 一周热门
- 最近发表
- 标签列表
-
- grid 设置 (58)
- 移位运算 (48)
- not specified (45)
- 导航栏 (58)
- context xml (46)
- scroll (43)
- dedecms模版 (53)
- c 视频教程下载 (33)
- listview排序 (33)
- characterencodingfilter (33)
- getmonth (34)
- label换行 (33)
- android studio 3 0 (34)
- html转js (35)
- 索引的作用 (33)
- checkedlistbox (34)
- xmlhttp (35)
- mysql更改密码 (34)
- 权限777 (33)
- htmlposition (33)
- 学校网站模板 (34)
- textarea换行 (34)
- 轮播 (34)
- asp net三层架构 (38)
- bash (34)