c++ - 复制矩阵的一部分并粘贴到另一个C++上

标签 c++ matrix copy

用户输入一个矩阵,并且输出必须是一个新的矩阵,该矩阵具有一个附加的零列。如果将脚本应用于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;
}

最佳答案

可变长度数组(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

关于c++ - 复制矩阵的一部分并粘贴到另一个C++上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62220253/

相关文章:

c++ - 从运行时加载的 Dll 调用主程序的方法

c++ - boost::context::basic_segmented_stack 不按需增长

c++ - 为什么 GCC 中的 -Wunused-variable 即使在静态常量上也会产生错误?

excel - 如何从不同的工作表复制并粘贴除第 1 行之外的所有内容

c++ - 如何复制红黑树,它的分配器应该是什么

c++ - 结构中 union 的 const 成员的问题

c++ - 使用 Rcpp 在 R 中使用矩阵是否有限制?

javascript - WebGl - 倾斜投影

r - 将矩阵的每一行与另一个矩阵中的同一行进行交互

matlab - 复制矩阵的一行或一列并将其插入下一行/列