C++的内置数组和STL array、STL vector

简介: C++的内置数组和STL array、STL vector

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

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对象中存储简单分配器的任何数据。
//代码效果参考:http://www.zidongmutanji.com/zsjx/513631.html

template
class Vector {
allocator 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 , 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.

在中定义的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 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 a0 = {1,2,3}; // error size not specified
array a1 = {"John's", "Queens' "}; // error: size not a constant expression
array 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.
//代码效果参考:http://www.zidongmutanji.com/bxxx/195220.html

如果您需要元素计数为变量,请使用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 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 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 a2;
// ...
Shape p1 = a1; // OK: disaster waiting to happen
Shape
p2 = a2; // error: no conversion of array 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.
//代码效果参考:http://www.zidongmutanji.com/zsjx/262771.html

“disaster”注释假定sizeof(Shape)<size of(Circle),因此通过Shape*下标Circle[]给出了错误的偏移量。与内置数组相比,所有标准容器都提供了这一优势。

ref

Bjarne Stroustrup, A Tour of C++ Third Edition

相关文章
|
4月前
|
人工智能 Java
Java 中数组Array和列表List的转换
本文介绍了数组与列表之间的相互转换方法,主要包括三部分:1)使用`Collections.addAll()`方法将数组转为列表,适用于引用类型,效率较高;2)通过`new ArrayList&lt;&gt;()`构造器结合`Arrays.asList()`实现类似功能;3)利用JDK8的`Stream`流式计算,支持基本数据类型数组的转换。此外,还详细讲解了列表转数组的方法,如借助`Stream`实现不同类型数组间的转换,并附带代码示例与执行结果,帮助读者深入理解两种数据结构的互转技巧。
104 1
Java 中数组Array和列表List的转换
|
4月前
|
JavaScript 前端开发 API
JavaScript中通过array.map()实现数据转换、创建派生数组、异步数据流处理、复杂API请求、DOM操作、搜索和过滤等,array.map()的使用详解(附实际应用代码)
array.map()可以用来数据转换、创建派生数组、应用函数、链式调用、异步数据流处理、复杂API请求梳理、提供DOM操作、用来搜索和过滤等,比for好用太多了,主要是写法简单,并且非常直观,并且能提升代码的可读性,也就提升了Long Term代码的可维护性。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
4月前
|
移动开发 运维 供应链
通过array.some()实现权限检查、表单验证、库存管理、内容审查和数据处理;js数组元素检查的方法,some()的使用详解,array.some与array.every的区别(附实际应用代码)
array.some()可以用来权限检查、表单验证、库存管理、内容审查和数据处理等数据校验工作,核心在于利用其短路机制,速度更快,节约性能。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
4月前
|
供应链 JavaScript 前端开发
通过array.every()实现数据验证、权限检查和一致性检查;js数组元素检查的方法,every()的使用详解,array.some与array.every的区别(附实际应用代码)
array.every()可以用来数据验证、权限检查、一致性检查等数据校验工作,核心在于利用其短路机制,速度更快,节约性能。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
4月前
|
Web App开发 存储 前端开发
别再用双层遍历循环来做新旧数组对比,寻找新增元素了!使用array.includes和Set来提升代码可读性
这类问题的重点在于能不能突破基础思路,突破基础思路是从程序员入门变成中级甚至高级的第一步,如果所有需求都通过最基础的业务逻辑来做,是得不到成长的。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
4月前
|
数据采集 JavaScript 前端开发
JavaScript中通过array.filter()实现数组的数据筛选、数据清洗和链式调用,JS中数组过滤器的使用详解(附实际应用代码)
用array.filter()来实现数据筛选、数据清洗和链式调用,相对于for循环更加清晰,语义化强,能显著提升代码的可读性和可维护性。博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
6月前
|
存储 算法 搜索推荐
【C++面向对象——群体类和群体数据的组织】实现含排序功能的数组类(头歌实践教学平台习题)【合集】
1. **相关排序和查找算法的原理**:介绍直接插入排序、直接选择排序、冒泡排序和顺序查找的基本原理及其实现代码。 2. **C++ 类与成员函数的定义**:讲解如何定义`Array`类,包括类的声明和实现,以及成员函数的定义与调用。 3. **数组作为类的成员变量的处理**:探讨内存管理和正确访问数组元素的方法,确保在类中正确使用动态分配的数组。 4. **函数参数传递与返回值处理**:解释排序和查找函数的参数传递方式及返回值处理,确保函数功能正确实现。 通过掌握这些知识,可以顺利地将排序和查找算法封装到`Array`类中,并进行测试验证。编程要求是在右侧编辑器补充代码以实现三种排序算法
106 5
|
5月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
1月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
42 0
|
1月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
108 0

热门文章

最新文章

  • 1
    Java 中数组Array和列表List的转换
    104
  • 2
    JavaScript中通过array.map()实现数据转换、创建派生数组、异步数据流处理、复杂API请求、DOM操作、搜索和过滤等,array.map()的使用详解(附实际应用代码)
    287
  • 3
    通过array.reduce()实现数据汇总、条件筛选和映射、对象属性的扁平化、转换数据格式、聚合统计、处理树结构数据和性能优化,reduce()的使用详解(附实际应用代码)
    460
  • 4
    通过array.some()实现权限检查、表单验证、库存管理、内容审查和数据处理;js数组元素检查的方法,some()的使用详解,array.some与array.every的区别(附实际应用代码)
    116
  • 5
    通过array.every()实现数据验证、权限检查和一致性检查;js数组元素检查的方法,every()的使用详解,array.some与array.every的区别(附实际应用代码)
    92
  • 6
    多维数组操作,不要再用遍历循环foreach了!来试试数组展平的小妙招!array.flat()用法与array.flatMap() 用法及二者差异详解
    75
  • 7
    别再用双层遍历循环来做新旧数组对比,寻找新增元素了!使用array.includes和Set来提升代码可读性
    75
  • 8
    Array.forEach实战详解:简化循环与增强代码可读性;Array.forEach怎么用;面对大量数据时怎么提高Array.forEach的性能
    49
  • 9
    深入理解 JavaScript 中的 Array.find() 方法:原理、性能优势与实用案例详解
    115
  • 10
    JavaScript 中通过Array.sort() 实现多字段排序、排序稳定性、随机排序洗牌算法、优化排序性能,JS中排序算法的使用详解(附实际应用代码)
    219