将 2D 数组作为函数参数,并返回 2D 数组作为函数的返回类型
Giving 2D Array as Function Parameter and returning 2D Array as return type of the Function
我正在尝试查找 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);
}
基本上数组大小必须在编译时知道,基本上它不能是一个可以有任何值、没有值或变化值的变量
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中