如何声明可从其他函数访问的二维数组?

时间:2014-04-13 18:20:23

标签: c++ arrays

我有一个简短的问题:

如果我想从其他函数访问二维数组,我应该将其定义为静态吗?如果是这样,我如何使用其他成员初始化它。  这是我的代码:

private:
    static double Q [][];
};

这是在名为firstpassagetime的函数中使用数组Q的部分:

HGlycation A1C;
int states = A1C.    
Q [states][states];
for ( int k = 0; k < states; k++)
{
    if ( k != j)
    {
        currenti =k;
        return (sum + ( Q[i][k]*firstpassagetime( k,j, n-1)));
    }
}

编辑:完整代码

#include<iostream>
#include<vector>

using namespace std;

class HGlycation
{
    public:
    double method1 (double L []); // based on the first-passage-time probabilities.
    double firstpassagetime(int i, int j, int n);
    private:
    int Numberofstates ;
    int g, c ; // model paramteres.
    static  double L[];
    static std:: double Q[][100];

};

//Q[100][100];


double HGlycation::method1 ( double L [])
{

    HGlycation A1C;
    int states = A1C.Numberofstates;
    for ( int i = 0; i < states;i++)
    {
        L[i] = i % states;

    }

    //A1C.Q [states][100];  // mine
    double P [states][states];  // get it from luise functions

    for ( int i =0 ; i < states; i++)
    {

        for (int j=0;j< states; j++)
        {
            if ( i==0 && j==0)
                Q[i][j]==1;
            else if ( i == 0 && j!=0)
                Q[i][j]=0;
            else if( i !=0 && j ==0)
                Q[i][j]= g*L[i] +c;
            else
                Q[i][j]= (1- (g*L[i]+c))* P[i][j];
            \\ the rest of the code
        }
    }
}

1 个答案:

答案 0 :(得分:1)

你需要做类似的事情。您应该始终在纯C数组上使用std :: vector或std :: array。

#include <vector>

struct A{
private:
    static std::vector<std::vector<double>> Q;

    static std::vector<std::vector<double>> vec_init(){
        std::vector<std::vector<double>> temp(100);
        for(int i = 0; i < 100; i++){
            Q[i] = std::vector<double>(100,0);
        }
        return temp;
     }
 };


 std::vector<std::vector<double>> A::Q = A::vec_init();

 int main(){
     //Would print but its private
     return 0;
 }

这将创建一个100x100的零初始化双精度网格。

编辑:更好!

struct A {
private:
   static std::vector<std::vector<double>> Q;
};

std::vector<std::vector<double>> A::Q(100, std::vector<double>(100,0));

int main(){
    return 0;
}