c++ - 基于伪代码编写的高斯消元中的std::bad_alloc

标签 c++ matrix c++14 gaussian

我使用了这个伪代码:

 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;
}

但是我得到这个错误:

terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

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

最佳答案

这里有一些问题。

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

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

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

关于c++ - 基于伪代码编写的高斯消元中的std::bad_alloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53295095/

相关文章:

performance - Matlab bsxfun() - 如何解释沿不同维度扩展时的性能差异?

c++ - 将函数指针数组中的函数指针作为模板参数传递

c++ - 如何检查 T 是否为聚合类型?

c++ - 为什么 C++ 不捕获这个异常?

c++ - 为什么 PNG 图像的标准输出有时会在 printf 中刷新到图像的一半?

c++ - 调整 2D 动态分配的大小

c++ - 线性重载: why clang fails where gcc compiles?

c++ - 如何解决命名空间 "' 中的 'std' 互斥体'未命名类型“?

c++ - 声明 Windows API 结构 (DCB) 的对象 - 错误 C4430 : missing type specifier - int assumed

r - 如何使用 `` ggplot 2`` 从数字矩阵绘制栅格