数组向量的内存布局是什么? [英] What is the memory layout of vector of arrays?

查看:169
本文介绍了数组向量的内存布局是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下

std::vector<std::array<int, 5>> vec(2)

是否提供2D阵列的连续存储块 有2行5个元素?

does it provide contiguous memory block of a 2D array with 2 rows of 5 elements?

据我所知,向量的向量

std::vector<std::vector<int>> vec(2, std::vector<int>(5))

在内存中提供两个 长度为5个元素 s 的连续数组 5个的内存布局.

provide the memory layout of two contiguous arrays of length 5 elements in different locations in memory.

数组的向量会相同吗?

推荐答案

数组没有任何间接寻址,而只是直接"存储它们的数据.也就是说,std::array<int, 5>字面连续包含五个int.而且,像矢量一样,它们不会在元素之间放置填充,因此它们是内部连续的".

Arrays do not have any indirection, but just store their data "directly". That is, a std::array<int, 5> literally contains five ints in a row, flat. And, like vectors, they do not put padding between their elements, so they're "internally contiguous".

但是, std::array对象本身可能大于其元素集!允许具有尾随的填充"(例如填充).因此,尽管有可能,但在第一种情况下,数据全部不一定是连续的.

However, the std::array object itself may be larger than the set of its elements! It is permitted to have trailing "stuff" like padding. So, although likely, it is not necessarily true that your data will all be contiguous in the first case.

An int
+----+
|    |
+----+

A vector of 2 x int
+----+----+----+-----+        +----+----+
| housekeeping | ptr |        | 1  |  2 |
+----+----+----+-----+        +----+----+
                   |          ^
                   \-----------

An std::array<int, 5>
+----+----+----+----+----+----------->
| 1  |  2 |  3 |  4 |  5 | possible cruft/padding....
+----+----+----+----+----+----------->

A vector of 2 x std::array<int, 5>
+----+----+----+-----+        +----+----+----+----+----+----------------------------+----+----+----+----+----+----------->
| housekeeping | ptr |        | 1  |  2 |  3 |  4 |  5 | possible cruft/padding.... | 1  |  2 |  3 |  4 |  5 | possible cruft/padding....
+----+----+----+-----+        +----+----+----+----+----+----------------------------+----+----+----+----+----+----------->
                   |          ^
                   \-----------

而且,即使是这样,由于使用别名规则,您是否能够使用单个int*导航所有10个数字也可能是另一回事!

And, even if it were, due to aliasing rules, whether you'd be able to use a single int* to navigate all 10 numbers would potentially be a different matter!

总而言之,十个int的向量将更清晰,完全打包并且使用起来可能更安全.

All in all, a vector of ten ints would be clearer, completely packed, and possibly safer to use.

对于向量的向量,向量实际上只是一个指针加上一些内部管理,因此是间接的(如您所说).

In the case of a vector of vectors, a vector is really just a pointer plus some housekeeping, hence the indirection (as you say).

这篇关于数组向量的内存布局是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆