【问题标题】:std::bad_alloc in Gaussian Elimination written based on a pseudo-code基于伪代码编写的高斯消除中的 std::bad_alloc
【发布时间】:2018-11-14 07:31:45
【问题描述】:

我使用了这个伪代码:

 h := 1 /* Initialization of the pivot row */
 k := 1 /* Initialization of the pivot column */
 while h ≤ m and k ≤ n
   /* Find the k-th pivot: */
   i_max := argmax (i = h ... m, abs(A[i, k]))
   if A[i_max, k] = 0
     /* No pivot in this column, pass to next column */
     k := k+1
   else
      swap rows(h, i_max)
      /* Do for all rows below pivot: */
      for i = h + 1 ... m:
         f := A[i, k] / A[h, k]
         /* Fill with zeros the lower part of pivot column: */
         A[i, k]  := 0
         /* Do for all remaining elements in current row: */
         for j = k + 1 ... n:
            A[i, j] := A[i, j] - A[h, j] * f
      /* Increase pivot row and column */
      h := h+1 
      k := k+1

编写这段代码(高斯消元法):

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

typedef std::vector<std::vector<int>> matrix;
typedef long long ll;

void inverse_matrix(matrix &mat)
{
    ll h = 1, k =1;
    auto m = mat.size(), n = mat[0].size();


    while (h <= m && k <= n)
    {
        ll i_max = 0;
        for (ll i = h; i <= m; ++i)
        {
            i_max = std::fmax(i, std::abs(mat[i][k]));
        }

        if (mat[i_max][k] == 0)
        {
            ++k;
        }

        auto temp = mat[h];
        mat[h] = mat[i_max];
        mat[i_max] = temp;

        for (auto j = h + 1; j <= m; ++j)
        {
            auto f = mat[j][k] / mat[h][k];
            mat[j][k] = 0;

            for (auto v = k + 1; v <= n; ++v)
            {
                mat[j][v] = mat[j][v] - mat[h][j] * f;
            }
        }

        ++h;
        ++k;
    }
}

int main() {
    matrix mat = {{2, 2}, {4, 5}};
    inverse_matrix(mat);

    return 0;
}

但我收到此错误:

在抛出 'std::bad_alloc' 的实例后调用终止 什么():std::bad_alloc

此应用程序已请求运行时以不寻常的方式终止它。 请联系应用程序的支持团队了解更多信息。

怎么了?我将伪代码复制到发球台上。

【问题讨论】:

  • 我相信你有未定义的行为,因为你的索引越界:for (auto j = h + 1; j &lt;= m; ++j) 所以不确定这里发生了什么。尝试使用编译器警告或编译器的 -fsanitize 标志来指导您
  • 我很惊讶您尝试计算 int 矩阵的逆 ...
  • 我不明白你对 std::fmax 的使用

标签: c++ matrix c++14 gaussian


【解决方案1】:

这里有一些问题。

首先,您没有正确复制代码(例如,伪代码的第 5 行 - 包括注释行)。您应该寻找的是最大值的索引,而不是将该值与索引进行比较。更糟糕的是,您这样做的方式最终只会存储最终比较,因为您会覆盖所有其他结果。

其次,伪代码运行从 1 到 n 的索引,您知道 C++ 不会,而是使用基于 0 的索引。至于错误,std::bad_alloc 表示分配失败,这很可能是以下行:auto temp = mat[h];,其中h 由于您的基于 1 的计数方法而超出范围。

也许作为旁注,您也可以用std::swap 替换您的交换,这可能会稍微提高性能,因为它可能会避免复制并依赖于移动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    相关资源
    最近更新 更多