c++ - 在 C++ 中通过输入创建和填充矩阵

标签 c++ vector matrix

我正在尝试用 C++ 编写一个能够乘以矩阵的程序。 不幸的是,我无法用 2 个 vector 创建矩阵。目标:我输入行数和列数。然后应该有一个用这些维度创建的矩阵。然后我可以通过输入数字来填充(例如 rows = 2 cols = 2 => Matrix = 2 x 2)矩阵。我用这两个代码试过了:(第二个在头文件中)

#include <iostream>
#include "Matrix_functions.hpp"

using namespace std;

int main ()
{
    //matrices and dimensions
    int rows1, cols1, rows2, cols2;
    int **matrix1, **matrix2, **result = 0;

    cout << "Enter matrix dimensions" << "\n" << endl;
    cin >> rows1 >> cols1 >> rows2 >> cols2;

    cout << "Enter a matrix" << "\n" << endl;

    matrix1 = new int*[rows1];
    matrix2 = new int*[rows2];

    // Read values from the command line into a matrix
    read_matrix(matrix1, rows1, cols1);
    read_matrix(matrix2, rows2, cols2);

    // Multiply matrix1 one and matrix2, and put the result in matrix result
    //multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);

    //print_matrix(result, rows1, cols2);

    //TODO: free memory holding the matrices

    return 0;
}

这是主要代码。现在带有read_matrix函数的头文件:

#ifndef MATRIX_FUNCTIONS_H_INCLUDED
#define MATRIX_FUNCTIONS_H_INCLUDED

void read_matrix(int** matrix, int rows, int cols)
{
    for(int i = 0; i < rows; ++i)
        matrix[i] = new int[cols];

}

//int print_matrix(int result, int rows1, int cols1)
//{
//    return 0;
//}

//int multiply_matrix(int matrix2, int rows2, int cols2, int matrix3, int rows3, int cols3, int result2)
//{
//    return result2;
//}

#endif // MATRIX_FUNCTIONS_H_INCLUDED

第一部分有效。我可以填写尺寸。但随后它打印:输入一个矩阵,然后程序退出。为什么我无法填写矩阵的数字?

我希望有人能帮助我。如果有不清楚的地方,请告诉我。

提前致谢:D (不要注意大部分评论;那些是用于其余乘法代码的)

最佳答案

你忘记了 cin 数字,试试这个:

void read_matrix(int** matrix, int rows, int cols)
{
    for (int i = 0; i < rows; ++i) {
        matrix[i] = new int[cols];
        for (int j = 0; j < cols; ++j) {
            cin >> matrix[i][j];
        }
    }
}

关于c++ - 在 C++ 中通过输入创建和填充矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813184/

相关文章:

c++ - C++ 中的 'vector<type[n]>' 是什么?

c++ - n 维 C++ 数组。这怎么可能?

c++ - 对于代码中指定范围之外的值,对角差分算法的输入不正确

c++ - 通过重载下标运算符()从矩阵获取 vector

c++ - 在 OpenGL 上画圆

c++ - 如何 std::bind 模板函数?

c++ - 多次排序容器,使用什么容器和什么方法

c++ - 使用 cmake 编译日期和时间

c++ - 在确定的时间内生成特定数字的随机序列

c++ - 如何使用字符串返回一个指向对象的唯一指针 vector 的迭代器来查找对象?