【问题标题】:How can I define large multidimensional arrays in c++ without getting this error?如何在 C++ 中定义大型多维数组而不会出现此错误?
【发布时间】:2021-08-20 18:31:30
【问题描述】:

我的编程知识非常基础,但通常足以满足我的需要。

我正在使用 Visual Studio 并尝试定义大小为 [20][20][20][10000] 的 4 维(可能更多)的大型数组。

起初我将一个数组定义为 int array[5][5][5][900],它工作正常。然后我尝试定义一个新数组,大小相同但名称不同,并在 chkstk.asm 上得到一个未处理的异常错误查找下一个较低的页面并进行探测 cs20: 子 eax, PAGESIZE ;减少 PAGESIZE 测试 dword ptr [eax],eax ;探测页面。 jmp 短 cs10

我尝试定义为双精度和长双精度,并使用向量,但似乎没有区别。我还想增加尺寸并可能增加更多尺寸。

有人可以解释一种简单的方法来制作这样的数组而不会发生这种情况吗?

数组元素只需要包含0或1

【问题讨论】:

  • 这个问题需要更多细节来帮助我们重现问题——最好是minimal reproducible example。但至少非常我们需要查看您的代码。
  • 对于那些好奇的人,int[20][20][20][10000] 在大多数机器上大约为 305MB,所以应该适合 RAM。

标签: c++ arrays multidimensional-array


【解决方案1】:

问题是您指定的数组将非常大(20 * 20 * 20 * 900 = 720 万)。由于该数据存储在堆栈中,因此您可能会看到堆栈溢出。

你可能想用new 分配这么大的东西,比如:

    auto test = new int[20][20][20][900];
    test[0][1][0] = 0;

    // when you're done with it, you'll need to delete though
    delete[] test;

这会将它放入(更大的)堆中

【讨论】:

【解决方案2】:

您可以考虑这种方法:

#include <vector>

int main()
{
    std::vector<std::vector<std::vector<std::vector<bool>>>> tab4;
    int n1 = 10;     // 1st dimension
    int n2 = 20;     // 2nd dimension
    int n3 = 30;     // 3rd dimension
    int n4 = 10000;  // 4th dimension

    tab4.resize(n1);
    for (auto& v : tab4)
    {
        v.resize(n2);
        for (auto& w : v)
        {
            w.resize(n3);
            for (auto& u : w)
            {
                u.resize(n4);
            }
        }
    }
    tab4[1][12][23][4000] = 9999;
}

优点:

  • 此代码是异常安全且无泄漏的
  • 如果需要,可以轻松调整矢量的大小。
  • 每个向量维度的大小不必是编译常量
  • 初学者不应接触裸指针,因为存在更健壮、安全和易于使用的替代方案。

缺点:

  • 需要更多代码(这不是一个严重的缺点)
  • 分配的内存不是连续的(这可能只对高级用户有些重要,可以绕过,但我不知道可以建议初学者的解决方案)

替代解决方案

如果向量的大小在编译时是固定的,则可以使用它。一个vector 用于自动分配堆上的内存,无需借助裸指针,operator new 等。

#include <array>
#include <vector>

int main()
{
    // vector [10][20][30][1000]
    std::vector<std::array<std::array<std::array<bool, 10000>, 30>, 20>> tab4 (10);

    tab4[1][12][23][4000] = 9999;
}

我个人喜欢std::,但有时数量太多。可以这样实现:

  using std::array;
  std::vector<array<array<array<bool, 10000>, 30>, 20>> tab4 (10);

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多