c++ - What is the memory layout of vector of arrays?
问题描述
can anybody explaine the memory layout of
std::vector<std::array<int, 5>> vec(2)
does it provide contiguous memory block of a 2D array with 2 rows of 5 elements?
To my understanding, the vector of vectors
std::vector<std::vector<int>> vec(2, std::vector<int>(5))
provide the memory layout of two contiguous arrays of length 5 elements in different locations in memory.
Will it be the same for the vector of arrays?
解决方案
Arrays do not have any indirection, but just store their data "directly". That is, a std::array<int, 5>
literally contains five int
s in a row, flat. And, like vectors, they do not put padding between their elements, so they're "internally contiguous".
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....
+----+----+----+-----+ +----+----+----+----+----+----------------------------+----+----+----+----+----+----------->
| ^
\-----------
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!
All in all, a vector of ten int
s 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).
推荐阅读
- javascript - 我今天遇到了 window.addEventListener 和 React Native 的问题
- android - 未解决的参考 layoutInflater Android 视图绑定
- javascript - 如何在jQuery / javascript中将多个对象合并为一个对象
- r - 有没有办法使用 R 在网站上查找重复的单词?例如一篇新闻文章
- python - python 2to3:如何选择性地启用修复程序并且只执行其中的一两个?
- http - ASP.NET Core Web 应用程序为每个请求返回不同的响应标头
- vue.js - 如何在静态生成的 NuxtJS 网站中添加身份验证
- html - 如何使文本出现在食谱图像的中心下方,并且与 css 之间的距离相等?
- azure - Azure Kubernetes 集群 - 从本地访问服务并与之交互
- php - 如何正确搜索整个字符串和格式