C++|内置数组、STL array、STL vector( 二 )

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 interfacevoid g(){array<int,10> a;f(a,a.size());// error: no conversionf(a.data(),a.size());// C-style useauto 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;// copya2[1] = 5;a1 = a2;// assignHowever, 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 happenShape* 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-

【C++|内置数组、STL array、STL vector】


推荐阅读