2015-09-25 18 views
0

我寫了一個程序如下:有關vector.push_back

if(i = 0) 
{ vector<int> data; 
    vector<int>::iterator it; 
    data.push_back(2); 
    data.push_back(3); 
    sort(data.begin(),data.end()); 
    it = data.begin(); 
} 

if(i = 0) 
{ vector<int> data; 
    vector<int>::iterator it; 
    data.push_back(5); 
    data.push_back(1); 
    sort(data.begin(),data.end()); 
    it = data.begin(); 
} 

如果我使用vector<int>兩次,它會自動釋放?我應該釋放內存嗎?

+0

您不使用向量的2次。 –

回答

4

當變量超出範圍時,局部變量的內存分配會自動刪除。

if(i == 0) 
{ 
    std::vector<int> data; //local variable 
} 
//allocation for 'data' is deleted automatically 
if(i == 0) 
{ 
    std::vector<int> data; //this is not the same vector as above 
    //in fact, the vector above no longer exists at this point 
} 
//allocation for 'data' is deleted automatically 
+0

非常感謝 – January