首页 > 解决方案 > 在 C++ 中分配大小为 10000 10000 3 的 3 维向量

问题描述

我正在制作一个图片编辑程序,我被困在分配内存中。我不知道发生了什么。

好的..所以当我这样做时:

std::vector<unsigned char> h;
for (int a = 0; a < 10000 * 10000 * 3; a++) {
    h.push_back(0);
}

这很好(对不起,我不得不这样做),但是当我这样做时:

std::vector<std::vector<std::vector<unsigned char>>> h;
for (uint32_t a = 0; a < 10000; a++) {
  h.push_back({});
  for (uint32_t b = 0; b < 10000; b++) {
    h.at(a).push_back({});
    for (uint32_t c = 0; c < 3; c++) {
      h.at(a).at(b).push_back(0xff);
    }
  }
}

我的内存使用量激增,并且出现错误:Microsoft C++ 异常:内存位置 0x009CF51C 处的 std::bad_alloc

我正在使用.bmp。

目前,代码处于测试模式,所以基本上是一团糟……我 15 岁,所以不要对我抱太大希望。

我正在寻找解决方案,但我发现的只是如何处理大整数等等......

如果你能给我另一个解决方案,但我希望我的代码尽可能地对初学者友好。

标签: c++

解决方案


这是由于vector<char>. 每个具有 3 个元素的对象不占用 3 个字节,但可能占用 4 个字节(由于重新分配策略),加上 3 个可能占用 3*8=24 个字节的指针。总体而言,您的结构占用的内存是它可能拥有的内存的 9.3 倍。

如果用数组替换内部向量,它将开始工作,因为数组没有这种开销:

std::vector<std::vector<std::array<unsigned char, 3>>> h;
for (uint32_t a = 0; a < 10000; a++) {
  h.emplace_back();
  for (uint32_t b = 0; b < 10000; b++) {
    h.at(a).emplace_back();
    for (auto &c : h.at(a).at(b)) {
      c = 0xff;
    }
  }
}

另一种选择是将较小的尺寸放在第一位。


推荐阅读