【问题标题】:Giving 2D Array as Function Parameter and returning 2D Array as return type of the Function将二维数组作为函数参数并返回二维数组作为函数的返回类型
【发布时间】:2023-03-14 12:35:01
【问题描述】:

我正在尝试查找 2D 矩阵的转置并想创建一个函数 将我的 2D 数组和 Matrix 的值数量作为输入并返回 二维矩阵的转置。 我用 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

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

【问题讨论】:

  • 请注意int wt_vect[1][n]n 是一个变量)不是(标准)C++。
  • 并且,请注意wt_vect[1] 访问second 元素;如果wt_vect 的第一个维度是1,你应该写wt_vect[0][i]

标签: c++ c++11 matrix


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    数组的大小基本上在编译的时候就知道了,基本上不能是一个可以有任何值、没有值或改变值的变量

    【讨论】:

    • 那我该如何解决这个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多