1

我想制作一个connectionsOf大小为 40 000 的 bool 矩阵。这是我的代码:

int index = 40000;
bool connectionsOf[index][index];

但是,当我在一个包含 37 000 个数字的文件上运行它来填充矩阵时,会出现分段错误。在stackoverflow上浏览,我发现这是因为索引号太高,它会炸毁堆栈。有没有办法使这个堆栈成为可能?比如静态、常量、动态、指针?如果是这样,我应该用什么替换我的代码?

4

4 回答 4

4

您可以通过在boost::dynamic_bitset周围编写包装器来模拟二维位数组(并且可能会节省一些内存)。

class BitMatrix
{
public:
    BitMatrix (int size) : size_(size), bits_(size_ * size_) {}
    void set(int x, int y) { bits_.set(y * size_ + x); }
    bool test(int x, int y) { return bits_.test(y * size_ + x); }
private:
    int size_;
    boost::dynamic_bitset bits_;
};

如果您在编译时知道大小,您也可以将此技术与std::bitset.

于 2013-05-08T16:49:13.513 回答
2

你在滥用堆栈。40'000 x 40'000 x sizeof(bool) = (至少) 800'000'000。很多(单个块中有 800MB)

尝试:

index = 40000;
bool** connections = new bool*[index];
for (int t = 0; t < index; ++t) {
    connections[t] = new bool[index];
}

确保也充分处理它(与上面相同,只是反向 - 首先迭代并处理数组元素,然后处理表本身)

于 2013-05-08T16:42:20.123 回答
2

您的问题的答案取决于您使用的编译器。对于 gcc,请参阅此问题。但是为什么需要在栈上而不是堆上分配这么大的数据块呢?而且,顺便说一句,您需要分配 200 x 200 数组来获得 40 000 个项目 (200^2)。

于 2013-05-08T16:21:43.810 回答
0

您应该能够通过编译器标志设置堆栈大小。

于 2013-05-08T16:19:22.273 回答