【问题标题】:Copy part of a matrix and paste on another one C++复制矩阵的一部分并粘贴到另一个 C++
【发布时间】:2020-06-05 16:41:18
【问题描述】:

用户输入一个矩阵,输出必须是一个新的矩阵,其中包含一个额外的零列。如果我们将脚本应用于 2 方矩阵,例如:{1,2,3,4},则新矩阵输出将是 2 行和 3 列:{1,2,32,3,4,0}。我不明白数字 32 的输出。

#include <iostream>

int main(){

    int m,n;

    std::cout << "Input the size of the square matrix :  ";
    std::cin >> m;
    n=m;

    int A[m][n]={};
    int M[m][n+1]={0};

    for (int i(0);i<m;i++){
        for(int j(0);j<n;j++){
            std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
            std::cin >> A[i][j];
            M[i][j]=A[i][j];                    
        }
    }
    for (int i(0);i<m;i++){
        for(int j(0);j<=n;j++){
            std::cout << M[i][j] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

【问题讨论】:

  • 你知道,我不确定可变长度数组如何处理初始化。这是一种狂野西部的领土,因为可变长度数组不是 C++ 的一部分。一些编译器增加了对使 C++ 更像 C 的支持,但您必须检查编译器的文档以了解它如何处理 int M[m][n+1]={0};
  • 由于 C++ 中 VLA 的目标与 C 中的 VLA 相同,因此这个 C 问题可能是相关的:Initializing a dynamically-sized Variable-Length Array (VLA) to 0
  • 在 g++ 上闲逛,看起来初始化请求大多被忽略了。仅设置第一个元素。
  • 旁注:A simple, fast, and safe dynamically-sized matrix class。作为额外的奖励,它还会自动初始化为全零。

标签: c++ matrix copy


【解决方案1】:

可变长度数组 (VLA) 是一个不可移植的 gcc 扩展,显然不会像您期望的那样初始化。

一种解决方案是改用std::vector,它是可移植的,可以做你想做的事,像这样:

#include <iostream>
#include <vector>

int main(){
    int m,n;
    std::cout << "Input the size of the square matrix :  ";
    std::cin >> m;
    n=m;

    std::vector <std::vector <int>> A;
    std::vector <std::vector <int>> M;
    A.resize (m);
    M.resize (m);

    for (int i = 0; i < m; ++i)
    {
        A [i].resize (n);
        M [i].resize (n + 1);
    }

    for (int i(0);i<m;i++){
        for(int j(0);j<n;j++){
            std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
            std::cin >> A[i][j];
            M[i][j]=A[i][j];    
            std::cout << "\n";
        }
    }

    for (int i(0);i<m;i++){
        for(int j(0);j<=n;j++){
            std::cout << M[i][j] << " ";
        }
        std::cout << "\n";
    }
}

Live demo

【讨论】:

  • 所以没有办法“手动”解决这个问题,不使用矢量类?
  • 是的,您可以memset 您的 VLA,如上面 user4581301 发布的链接中所述。但是如果你正在编写 C++,你不应该使用 VLA——就像我说的那样,那里是非标准的。
  • 我有几个非标准的原因:VLA 的完全sizeof 的编译时行为,它们是允许用户触发堆栈溢出的非常好的方法。在许多系统上输入 250 的 m,然后坐下来观看乐趣。
【解决方案2】:

在 C 的糟糕旧时代,您可以 realloc() 更大的数组和 memset() 新列(仅适用于最后一个维度,其中项目相邻)。

【讨论】:

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