int main(){
int row1, column1;
cout << "How many rows for first matrix?";
cin >> row1;
cout << "How many columns first matrix?";
cin >> column1;
int org[row1][column1];
cout << "Enter the elements of first matrix: ";
for(int i=0;i<row1;i++){
for(int j=0;j<column1;j++){
cin>>org[i][j];
}
}
for(int i=0;i<row1;i++){
for(int j=0;j<column1;j++){
cout<<org[i][j];
}
cout<<endl;
}
matrixreshape sol;
我在将
column1
、row1
和矩阵org
传递到matrixReshape
函数中时遇到问题。
cout<<sol.matrixReshape(vector<vector<int> org[row1][column1],row1, column1);
matrixReshape
函数如下:
class matrixreshape {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
vector<vector<int>> newMatrix(r, vector<int>(c, 0));
方法matrixReshape
需要一个vector<vector<int>>
作为实际参数。您正试图将无法直接转换的2D VLA传递给它。
您需要使用vector<vector<int>>
进行输入,并将其传递给matrixReshape
。
这里有一个例子:
vector<vector<int>> org( row1 );
for ( int i = 0; i < org.size(); i++ )
{
org[i].resize( column1 );
for ( int j = 0; j < org[i].size(); j++ )
{
cin >> org[i][j];
}
}
// and then pass it
matrixreshape sol;
cout << sol.matrixReshape( org, row1, col1 );
或者,对于C++11的循环范围,它会是这样的:
std::size_t rows {0};
std::size_t cols {0};
std::cin >> rows >> cols;
std::vector<std::vector<int>> matrix( rows );
for ( auto& r : matrix )
{
r.resize( cols );
for ( auto& c : r )
{
std::cin >> c;
}
}
matrixreshape sol;
std::cout << sol.matrixReshape( matrix, rows, cols );
以下是一个完整的工作示例:https://godbolt.org/z/XPwRMq
此外,您不需要将行和列信息传递给matrixReshape()
方法,因为std::vector
具有size()
方法。如果你需要的话,你可以用它。
另一件事是,您必须为该类型重载流插入运算符<<
才能使用std::cout
打印它。
这里有一个例子(现场(:
#include <iostream>
#include <vector>
using Matrix = std::vector<std::vector<int>>;
std::ostream& operator<<( std::ostream& os, const Matrix& m )
{
for ( const auto& r : m )
{
for ( const auto& c : r )
{
os << c << ' ';
}
os << 'n';
}
return os;
}
int main()
{
const Matrix m
{
{ 1, 2 },
{ 3, 4 }
};
std::cout << m;
return 0;
}
输出:
1 2
3 4