是的std ::阵列的连续内存? [英] Is the memory in std::array contiguous?
问题描述
在 STD内存::阵列
连续?在下面的有效/好的做法呢?
Is the memory in std::array
contiguous? Is the following valid/good practice?
std::array<type1,Num> arr = //initialize value
type1 * ptr = &arr[0];
我能然后通过 PTR
来期待C数组功能?
推荐答案
是的,它是连续的,因为它基本上是(实际上)一个键入ARR [10];
,但一样的界面STL。它也不会衰减到对挑衅的指针。
Yes, it is contiguous, as it is basically (and actually) a type arr[10];
, but with STL like interface. It also doesn't decay to a pointer on the slightest provocation.
您可以安全通过&放大器;常用3 [0]
来期待一个C风格的数组的函数,这是它的设计目标。但是要与STL算法使用它,只需要使用开始
和结束
功能:
You can safely pass &arr[0]
to a function expecting a C-style array, that's the design goal of it. To use it with the STL algorithms however, just use the begin
and end
functions:
// either members
std::sort(arr.begin(), arr.end());
// or free from <iterator>
std::sort(std::begin(arr), std::end(arr));
有关语言的律师组成部分,§23.3.2.1[array.overview] P1
:
头&LT;阵列GT;
定义存储对象的固定大小序列类模板。阵列支持随机访问迭代器。 T,N&GT; 商店 N
类型的元素 T $
阵列与LT的实例C $ C>,使
尺寸()==ñ
是不变的。 的的元素数组
存储连续,这意味着如果 A
是阵列&LT; T,N&GT;
则服从身份&放大器;一个[N] ==&放大器;一个[0] + N
所有 0℃; = N&LT; ñ
。
The header
<array>
defines a class template for storing fixed-size sequences of objects. An array supports random access iterators. An instance ofarray<T, N>
storesN
elements of typeT
, so thatsize() == N
is an invariant. The elements of anarray
are stored contiguously, meaning that ifa
is anarray<T, N>
then it obeys the identity&a[n] == &a[0] + n
for all0 <= n < N
.
和§23.3.2.1[array.overview] P2
:
数组是一个集合体(8.5.1),可以使用语法被初始化
An array is an aggregate (8.5.1) that can be initialized with the syntax
-
阵列&LT; T,N&GT; A = {
的初始化列表的};
array<T, N> a = {
initializer-list};
此外, P3
,列出的std ::阵列
成员:
T elems [N]; //只博览会
结果
[注:的成员变量 elems
显示为博览会上,要强调的是,阵列
是一类集合。名称 elems
不是阵列
的接口的一部分。的末端笔记的]
T elems[N]; // exposition only
[ Note: The member variableelems
is shown for exposition only, to emphasize thatarray
is a class aggregate. The nameelems
is not part ofarray
’s interface. —end note ]
这篇关于是的std ::阵列的连续内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!