2013-06-19 34 views
0

我遇到了一個問題。我試圖創建一個dll,它可以計算兩個點之間的距離,當我發送兩組不同的值時。 然而,當我在第二組中值的發送,我意識到我的第一組值也水漲船高陣列中丟失(數組被用來存儲值)在C++中創建一個用於不斷計算數學函數的dll

下面是我的代碼:

int click = 0; //click is used to measure the number of times i have clicked, ie to say the number of times im injecting new (a,b) points into the function below. 

double MeasureDistance(double a, double b) 
{ 
    /******* Create Array to Store The Points ********/ 

    /** Initializing the array **/ 
    double xDistance =0; 
    double yDistance =0; 
    double TDistance = 0; 
    static double **Array; 
    int column = 0; //used to toggle the column number 
    int width = 100; 
    int height = 100; 
    Array = new double *[width]; 
    for (int i=0; i <width; i++) 
    { 
     Array [i] = new double [height]; 
    } 

    /*** Now a and b are stored inside the Array[0][0] ***/ 

    for (column =0; column <2; column ++) 
    { 
     if ((column % 2)==0) 
     { 
      Array [click][column] = a; //storing at [0,0] 
     } 
     else 
     { 
      Array [click][column] = b; //storing at [0,1] 
     } 
    } 
       for (int row = 2; row < click; row ++) 
    { 
     for (column = 0; column <2; column ++) 
     { 
      if ((column % 2) == 0) 
      { 
       xDistance = Array [0][column] - Array [row][column]; 
      } 
      else 
      { 
       yDistance = Array [0][column] - Array [row][column]; 
      } 
     } 

     TDistance = sqrt((xDistance * xDistance) + (yDistance * yDistance)); 
    } 

/*** Clearing up of array ***/ 
    for (int i = 0; i < width; i++) 
    { 
     delete[] Array[i]; 
    } 
    delete[] Array; 


click++; 
    return TDistance ; 
} 

我意識到,當我注入第二組a和b值時,我的數組[0] [0]和[0] [1]中的值丟失,但我的第二組值存儲在[1] [0]和[1] [1]。任何想法如何我可以運行此腳本而不會丟失以前的值? 感謝提前加載。編輯代碼以清除一些查詢。

+1

每次調用函數時,所有的自動變量初始化。除此之外,你並不是在''刪除'你的'數組',這將導致你的進程最終餓死。 –

+0

分配時數組下標中的「click」是什麼? – arne

+0

@ bash.d不僅自動變量被重新初始化,數組也會被覆蓋,所以難怪數值「消失」了。它們只是留在舊數組中,新數組當然是空的。 – arne

回答

2

用行Array = new double *[width];你正在初始化你的數組在每個函數調用。如果您需要存儲值(我非常懷疑),最好使用靜態初始化向量。但通常它是一個很糟糕的想法讓功能的結果依賴於以前的調用。如果你真的需要積累狀態,考慮爲此創建一個函數對象。

編輯:

與函數對象,你可以改變operator()和數據結構通過成員變量來保存你的數據改變算法的行爲。

2日編輯: 你可能想是這樣的:

struct MeasureDistance { 
    double last_x; 
    double last_y; 

    MeasureDistance() : last_x(0), last_y(0) {} 
    double operator()(double new_x, double new_y) { 
    double diff_x=last_x-new_x; 
    double diff_y=last_y-new_y; 
    double result=sqrt(diff_x*diff_x,diff_y*_diff_y); 

    last_x=new_x; 
    last_y=new_y; 

    return result; 
}; 

MeasureDistance md; 
cout 
    << md(0.0, 1.0) << '\n' //prints 1 
    << md(2.0, 1.0) << '\n' //prints 2 
    ; 
+0

-1用於推薦一個靜態變量。推薦一個對象更好,但不是必需的:只要將一個引用傳遞給例如一個std :: vector < double >作爲該函數的額外參數就可以做到這一點 – stijn

+0

@stijn好的,我會更清楚地表明它是一個壞主意。但是一個函數對象比一個額外的參數要好。你可以在不改變接口的情況下改變實現。看看http://www.boost.org/doc/libs/1_53_0/doc/html/accumulators.html顯示瞭如何實現積累接口。 –

+0

即時通訊C++新手。所以我真的不明白。有沒有可供我參考的例子? – user2500220

相關問題