2d std::vector 连续内存? [英] 2d std::vector Contiguous Memory?

查看:41
本文介绍了2d std::vector 连续内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码,它分配了一个 2d std::vector<std::vector<int>> 大小为 5 x 3 并打印每个元素的内存地址:

#include #include <向量>int main() {整数 n = 5, m = 3;std::vector>vec(n, std::vector<int>(m));for (int i = 0; i < n; ++i) {for (int j = 0; j 

输出:

0x71ecc0 0x71ecc4 0x71ecc80x71ece0 0x71ece4 0x71ece80x71ed00 0x71ed04 0x71ed080x71ed20 0x71ed24 0x71ed280x71ed40 0x71ed44 0x71ed48

当然,对于固定行,每一列在内存中都是连续的,但行不是.特别是,每一行都比前一行的开头多 32 个字节,但由于每行只有 12 个字节,这留下了 20 个字节的间隙.例如,因为我认为 vectors 分配连续的内存,所以我希望第二行的第一个地址是 0x71eccc.为什么不是这种情况,vector 如何决定给予多少差距?

解决方案

向量的开销大小不是 0.向量的最后一个元素和下一个向量的第一个元素之间有 24 个字节.试试这个:

cout <<sizeof(std::vector) <<结束;

您会发现输出为 24(可能是因为您实现了 std::vector 和编译器等).

如果您希望元素实际上是连续的,则需要执行以下操作:

  1. 使用 std::array<std::array<int>> 没有开销(仅 c++11).请注意,这不能调整大小.
  2. 使用std::vector和公式row * numRows + col来访问row, col的元素.

Consider the following code, which allocates a 2d std::vector<std::vector<int> > of size 5 x 3 and prints the memory addresses of each element:

#include <iostream>
#include <vector>

int main() {
  int n = 5, m = 3;
  std::vector<std::vector<int> >vec (n, std::vector<int>(m));

  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      std::cout << &(vec[i][j]) << " ";
    }
    std::cout << "\n";
  }
}

Output:

0x71ecc0 0x71ecc4 0x71ecc8 
0x71ece0 0x71ece4 0x71ece8 
0x71ed00 0x71ed04 0x71ed08 
0x71ed20 0x71ed24 0x71ed28 
0x71ed40 0x71ed44 0x71ed48 

Of course, for a fixed row, each column is contiguous in memory, but the rows are not. In particular, each row is 32 bytes past the start of the previous row, but since each row is only 12 bytes, this leaves a gap of 20 bytes. For example, since I thought vectors allocate contiguous memory, I would have expected the first address of the second row to be 0x71eccc. Why is this not the case, and how does vector decide how much of a gap to give?

解决方案

The overhead size of a vector is not 0. You have 24 bytes between the last element of your vector and the first element of the next vector. Try this:

cout << sizeof(std::vector<int>) << endl;

You will find the output to be 24 (Likely for your implementation of std::vector and compiler etc). Live example which happens to match.

You can imagine the vector layout like this:

If you want your elements to actually be contiguous then you need to do:

  1. Use a std::array<std::array<int>> for no overhead (c++11 only). Note that this cannot be resized.
  2. Use std::vector<int> and the formula row * numRows + col to access the element for row, col.

这篇关于2d std::vector 连续内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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