如何让函数作用于非参数变量?

问题描述

我正在尝试编写一个函数,该函数将接收多个索引并根据这些索引处的数组中的值来执行某些操作。如果我不将数组声明为函数的参数(它将始终在相同的两个数组上运行),则不会在此范围内声明X / Y,但是如果我尝试声明它们,则会出现“错误:声明” X”作为多维数组必须具有除第一维之外的所有维的边界。”并且直到运行时才知道边界。

函数中是否有任何方法可以做到这一点,还是每次都必须在main中显式编写代码

代码

double foo(int A,int B,int t){//A,B,and t are indices 
  int x = X[A][t]-X[B][t]; //X and Y are 2D arrays
  int y = Y[A][t]-Y[B][t];
  double d;
  //do some math ...
  return d;
}

int main{
.
.
.
int X[nPeople][tMax]={0};
int Y[nPeople][tMax]={0};
.
.
.
for(int t=0; t<tMax; t++){
  for(int n=0; n<nPeople; n++){
    foo(n,a,t);
  }
}
.
.
.
return 0;
}

解决方法

有多种方法:

1-使用内置std :: vector库,并包含以下内容:

#include <vector>

向量是动态数组,因此在初始化它们时,它们没有严格的容量,您永远无法更改。相反,随着您推入或插入的每个元素,它们都会变得更大。据我所知,您正在处理矩阵,因此您需要二维数组,没问题。这是它的代码:

std::vector<std::vector<int> > 

2-使用全局变量。在函数外部声明的变量被认为是全局变量,因此它们对其下面的每个函数都是可见的。尽管它可能会引起大量问题,但由于它可能会引起大量问题,因此,它不被认为是良好的编码习惯,如果您有足够的信心确保它不会对代码的安全性/清洁性造成威胁,请继续使用它!

3-使用动态分配的数组并将指针作为参数传递,以便您可以处理所需的任何大小

,

函数可以通过几种方式处理数据:

  • 使用全局数据:

    std::vector<std::vector<int>> X;
    std::vector<std::vector<int>> Y;
    
    double foo(int A,int B,int t){ //A,B,and t are indices 
      int x = X[A][t]-X[B][t]; // X and Y are global 2D arrays
      int y = Y[A][t]-Y[B][t];
      double d;
      //do some math ...
      return d;
    }
    

    不幸的是,示例代码中显示了太多次,但是(可变)全局变量存在很多问题(难以测试,难以重用代码,难以推理代码)

  • 将它们作为参数传递:

    double foo(const std::vector<std::vector<int>>& X,// X and Y are 2D arrays
    
               const std::vector<std::vector<int>>& Y,// As we can see,so unneeded comment
               int A,and t are indices 
      int x = X[A][t]-X[B][t];
      int y = Y[A][t]-Y[B][t];
      double d;
      //do some math ...
      return d;
    }
    
  • 使用类将它们绑定:

    class C
    {
        std::vector<std::vector<int>> X;
        std::vector<std::vector<int>> Y;
     public:
        double foo(int A,and t are indices 
          int x = X[A][t]-X[B][t]; // X and Y are member 2D arrays (it should be trivial (`this->` might help),so comment not needed neither)
          int y = Y[A][t]-Y[B][t];
          double d;
          //do some math ...
          return d;
        }
    };
    

    注意创建连贯的类,并避免使用god class(默认值与全局默认值相同)。