c++ - 在 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 岁,所以不要对我抱太大希望。
我正在寻找解决方案,但我发现的只是如何处理大整数等等......
如果你能给我另一个解决方案,但我希望我的代码尽可能地对初学者友好。
解决方案
这是由于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;
}
}
}
另一种选择是将较小的尺寸放在第一位。
推荐阅读
- python-3.x - 用整数除浮点数
- android - ANDROID STUDIO 4.0 错误(开放阶段结束时没有进展)
- python - 在 Python 的 Pip 中,如何搜索与版本模式匹配的包的所有可能版本?
- javascript - 事件监听器和转换 JS
- c - 我需要使用 do/while 循环获得两个限制之间的值。当我在 while() 中放置两个条件时,代码会中断
- firebase - Streambuilder 帮助 Flutter Firebase 存储
- java - 角/弹簧靴| 错误:SyntaxError:“JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符”
- linux - 让 apache 只读取一个 php 文件
- google-chrome - 触摸自动在 Chromium 中的文本框上显示上下文菜单
- apache-ftpserver - 我们可以使用 Apache FTP 客户端执行 CPYTOIMPF 命令吗?