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



我正在尝试编写一个函数,该函数将接收多个索引,并根据这些索引处数组中的值执行某些操作。如果我不将数组声明为函数的参数(它将始终在相同的两个数组上操作(,我得到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::矢量库,包括以下内容:

#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, int B, int t){ //A, B, 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, int B, int t){ //A, B, 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类(它们的默认值和global基本相同(。

最新更新