2012-03-11 75 views
0

我需要使用列表int[2]。我嘗試使用STL中的列表,但在嘗試訪問列表時收到奇怪的結果。在C++中使用<int*>列表

我保存的[-1,+1]所有不同組合在列表中,但是當我試圖讓他們中的一個,它總是(1,1)

這裏是我的代碼:

#include <iostream> 
#include <list> 

using namespace std; 

int main (void){ 
    list<int*> test; 
    int x=0,y=0,i,j,k,l; 
    int *pin=new int[2]; 
    for (k = x-1; k <= x+1; k++) { 
     for (l = y-1; l <= y+1; l++) { 
      pin[0] = k; 
      pin[1] = l; 
      cout<<"inserting into list: "<<k<<" "<<l<<endl; 
      test.push_back(pin); 
     } 
    } 
    while(!test.empty()){ 
     pin=test.back(); 
     std::cout<<"List contains: "<<pin[0]<<" "<<pin[1]<<std::endl; 
     test.pop_back(); 
    } 
} 
+1

爲什麼不用int來代替int [2]?這樣你不必擔心再次刪除數組。 – 2012-03-11 11:35:55

回答

3

您分配一個單一引腳new,並添加多次,只是改變了值。

換句話說,你加銷到列表,改變它,到列表中相同的引腳現有的引用也會改變。最後,列表中的所有引腳都將具有最後一個插入的值。

+0

謝謝我看到發生了什麼 – 2012-03-11 11:43:33

2

您只爲內存分配了一個int[2],並且您在for循環中使用了相同的內存。看看下面的代碼:

#include <iostream> 
#include <list> 

using namespace std; 

int main (void){ 
    list<int*> test; 
    int x=0,y=0,i,j,k,l; 
    int *pin; 
    for (k = x-1; k <= x+1; k++) { 
     for (l = y-1; l <= y+1; l++) { 
      pin = new int[2]; /* allocate memory for each element */ 
      pin[0] = k; 
      pin[1] = l; 
      cout<<"inserting into list: "<<k<<" "<<l<<endl; 
      test.push_back(pin); /* add the address of above allocated memory to the list */ 
     } 
    } 
    while(!test.empty()){ 
     pin=test.back(); 
     std::cout<<"List contains: "<<pin[0]<<" "<<pin[1]<<std::endl; 
     test.pop_back(); /* delete the pointer from the list */ 
     delete[] pin; /* free the allocated memory */ 
    } 

} 
2

好吧首先,你爲什麼需要使用您的列表中int[2]?你可以簡單地使用一個

std::list<std::vector<int> > test; 

std::list<std::pair<int,int> > test; 

對這一問題。然而,無論如何讓回到你的問題:

您正在爲您的陣列曾經在這裏分配存儲:

int *pin=new int[2]; 

,然後你進入循環從來沒有分配新的存儲。 所以每次訪問pin喜歡在這裏

// Loop start 
pin[0] = k; 
pin[1] = l; 
// ... 
test.push_back(pin); 
// Loop end 

總是引用相同的內存位置,你最終會具有相同的指針指向相同的內存地址填寫各地的清單。

如果您已經使用了一個向量列表,那麼該錯誤首先不會發生,如果您必須分配存儲空間,請務必在每次循環體啓動時執行此操作。取得 也絕對謹慎DEALLOCATE一旦你完成數據的分配存儲。