将 2D 数组作为函数参数,并返回 2D 数组作为函数的返回类型

Giving 2D Array as Function Parameter and returning 2D Array as return type of the Function

本文关键字:函数 数组 2D 返回类型 返回 参数      更新时间:2023-10-16

我正在尝试查找 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:错误:数组绑定不是"]"标记之前的整数常量 7:32:错误:在","标记之前应为"(" 7:34:错误:"int"之前应存在非限定 id

请帮助我使用函数找到转置。 提前致谢

如果你使用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);
}

基本上数组大小必须在编译时知道,基本上它不能是一个可以有任何值、没有值或变化值的变量