【发布时间】:2013-09-15 13:54:29
【问题描述】:
我正在尝试用 C++ 编写一个能够将矩阵相乘的程序。 不幸的是,我无法从 2 个向量中创建一个矩阵。目标:我输入行数和列数。然后应该有一个使用这些维度创建的矩阵。然后我可以通过输入数字来填充(例如 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 (不要关注大部分的 cmets;那些是用于其余乘法代码的)
【问题讨论】:
-
首先,不要使用指针。使用
std::vector。 -
认为缺少cin来获取矩阵数据
-
要继续,程序会退出,因为您实际上没有任何代码可以从用户那里读取矩阵值的输入。
-
使用一维方法(
std::vector并且只有一个)并查看stackoverflow.com/questions/17259877/… 为什么。 -
最后,不要将非内联或非模板代码放在头文件中。在头文件中声明函数,但在源文件中定义它们。