我试图找到2D矩阵的转置,并希望创建一个函数,以我的2D数组和矩阵的值数作为输入,并返回2D矩阵的转置。我用C++编写了以下代码
#include <iostream>
#include <string>
using namespace std;
//int** transpose(int arr[][] , int n);
int k=2;
int ** transpose(int wt[1][k] , int n )
{
int trans[n][1];
for(int i=0;i<n;i++)
{
trans[i][1] = wt[1][i];
}
return trans ;
}
int main()
{ int n;
cin >> n;
int wt_vect[1][n];
for( int i=0;i<n;i++)
{
wt_vect[1][i] = 0.7;
}
int trans[n][1] = transpose(wt_vect , n);
}但是,获得错误日志如下所示
7:30: error:数组绑定不是“]”令牌7:32:“预期”之前的整数常数,“令牌7:34:错误:在”int“之前的预期非限定-id
请帮我找到转置功能。提前谢谢
发布于 2017-07-20 20:09:59
如果您使用C++,我建议您避免使用C样式数组。
如果您知道维度的运行时,可以使用std::array。
在您的情况下(第二维度知道运行时),您可以使用std::vector。
下面是一个完整的示例
#include <vector>
#include <iostream>
#include <stdexcept>
template <typename T>
using matrix = std::vector<std::vector<T>>;
template <typename T>
matrix<T> transpose (matrix<T> const & m0)
{
// detect the dim1 of m0
auto dim1 = m0.size();
// detect the dim2 of m0 (throw id dim1 is zero)
auto dim2 = m0.at(0U).size();
for ( auto const & r : m0 )
if ( dim2 != r.size() )
throw std::runtime_error("no consistent matrix");
// new matrix with switched dimension
matrix<T> ret(dim2, std::vector<T>(dim1));
// transposition
for ( auto i = 0U ; i < dim1 ; ++i )
for ( auto j = 0U ; j < dim2 ; ++j )
ret[j][i] = m0[i][j];
return ret;
}
int main ()
{
std::size_t n;
std::cin >> n;
matrix<int> mat(1U, std::vector<int>(n));
for ( auto i = 0U ; i < n ; ++i )
mat[0U][i] = 7;
auto tam = transpose(mat);
}发布于 2017-07-20 19:36:52
基本上,数组大小必须在编译时知道,基本上不能是一个变量,不能有任何值、没有值或更改值。
https://stackoverflow.com/questions/45223632
复制相似问题