如何从函数传递数组2d作为参数并返回此函数数组2d?

时间:2019-06-15 13:21:22

标签: c++

所讨论的问题涉及一个迭代过程,其中对象“ am”随该过程而改变(循环)。因此,我需要创建一个“ res”对象,该对象将存储要在另一个过程的同一过程中使用的Tfunc函数的结果。但是,我不能这样做。我是C ++编程的一个很好的初学者。我是R语言的程序员。

我的操作系统是使用ide代码块的ubuntu 16.04。

#include <iostream>
#include <cmath>
#include <cstdio>

using namespace std;

const int k = 3;

double Tfunc(double Told[k][k], double amm, int K);

int sample(int x);

int main(){
 int i, j;
 double am = 50;
 double told[k][k]{
  {1,0,0},
  {0,1,0},
  {0,0,1}
};

  double res;

  res = Tfunc(told, am, k);

  for(i=0;i<k;i++){
      for(j=0;j<k;j++){
          cout << res[i][j] << " ";
      }
      cout << "\n";
  }

  return 0;
}

double Tfunc(double Told[k][k], double amm, int K)
{
 int id1;
 int id2;
 int id3;

 id1 = sample(K);
 id2 = sample(K);
 id3 = sample(K);

 while(id2 == id3){
  id3 = sample(K);
 }

 Told[id1][id2] = Told[id1][id2] + amm;
 Told[id1][id3] = Told[id1][id3] - amm;

 return Told;
}

int sample(int x)
{
 srand(time(NULL)); //initialize the random seed

 int RandIndex = rand() % (x); 
 return RandIndex;
}

1 个答案:

答案 0 :(得分:0)

首先,也许这是问题的根本原因之一,您没有将二维数组正确传递给子函数。

您可以将其作为参考或指针传递。然后,您还可以在子函数中修改作为参数给出的数组。

请阅读here

然后,在现代C ++中,您将针对目的使用STL容器。对于二维材料,您需要创建一个容器容器。所以是std :: vector的std :: vector或std :: array的std :: array。

Tfunc将返回该容器容器并使用RVO(返回值优化)。因此,不会损失任何复杂性。

我为您创建了一个示例文件。这只是一种可能的解决方案。有很多。

#include <iostream>
#include <random>
#include <iterator>
#include <algorithm>
#include <array>

constexpr size_t MatrixDimension = 3;
using DoubleArray = std::array<double, MatrixDimension>;
using Matrix = std::array<DoubleArray, MatrixDimension>;

constexpr Matrix StartMatrix{{
 {1.0, 0.0, 0.0},
 {0.0, 1.0, 0.0},
 {0.0, 0.0, 1.0}
}};

size_t randomIndex()
{
    std::random_device randomDevice;    // Obtain a random number from hardware
    std::mt19937 randomGenerator(randomDevice());  // Seed the generator
    std::uniform_int_distribution<size_t> distribution(0, MatrixDimension-1); // Range
    return distribution(randomGenerator);
}

Matrix Tfunc(const Matrix& givenMatrix, double amm)
{
    size_t index1{ randomIndex() }; // Set indices with random values
    size_t index2{ randomIndex() };
    size_t index3{ randomIndex() };

    while (index2 == index3) {          // Make sure that index 2 is not equal index 3
        index3 = randomIndex();
    }
    Matrix calculatedMatrix{};

    calculatedMatrix[index1][index2] = givenMatrix[index1][index2] + amm;
    calculatedMatrix[index1][index3] = givenMatrix[index1][index3] - amm;

    return calculatedMatrix;
}

int main()
{
    constexpr double amm{ 50.0 };
    Matrix result = Tfunc(StartMatrix, amm);  // Apply Tfunc to matrix

    // Debug Output.  Print matrix to std::cout
    std::for_each(result.begin(), result.end(), [](DoubleArray &da) {std::copy(da.begin(), da.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << '\n'; });

    return 0;
}

顺便说一句。我不知道您的程序的目的。但是我认为您想在TFunc中拥有3个不同的索引。这不能保证。 2个可以相同。

我希望这会有所帮助。 。