2011-11-04 85 views
-1

我有一個簡單的函數,它在向量中仍存在元素時循環。在循環內部,使用pop_back()從矢量的末尾彈出單個元素。由於某種原因,我的代碼每次調用時都會刪除2個元素。Vector pop_back()刪除多於1個條目

vector<Vertex> vertices; 

while (vertices.size() != 0) { 
    std::cerr << "We are in the loop, size: " << vertices.size() << std::endl; 
    Vertex tmp = vertices.back(); 
    // do stuff with tmp, not shown here; 
    vertices.pop_back(); 
} 

輸出如下:

We are in the loop, size: 3 
We are in the loop, size: 1 

爲了澄清,這是上面的確切的代碼的輸出。

編輯:

vector<Vertex> vertices; 

while (vertices.size() != 0) { 

    Vertex tmp = vertices.back(); 
    std::cerr << "We are in the loop, size: " << vertices.size() << std::endl; 
    vertices.pop_back(); 
    std::cerr << "We are in the loop, size: " << vertices.size() << std::endl; 
} 

輸出:

We are in the loop, size: 3 
We are in the loop, size: 1 
We are in the loop, size: 1 
We are in the loop, size: 0 

編輯2:

我改變了我實現從向量雙端隊列。使用完全相同的命令,我設法實現所需的輸出:

We are in the loop, size: 3 
We are in the loop, size: 2 
We are in the loop, size: 2 
We are in the loop, size: 1 
We are in the loop, size: 1 
We are in the loop, size: 0 

仍然無法解釋之前的行爲;感謝大家的幫助。

+11

$ 100錯誤是「此處未顯示」。另外,總是使用'!empty()'而不是'size()!= 0'。 –

+3

在彈出之前打印出大小。您可能會意外彈出/刪除省略代碼中其他位置的元素。 – Kevin

+0

在pop_back()調用之前,您期望的大小是多少? – aschepler

回答

3

由於Kerrek SB提到的錯誤是不是在給出的代碼,我試過下面的代碼,它工作正常。

#include <iostream> 
#include <vector> 

int main (int argc, char **argv) { 
    std::vector<int> v; 
    for (int i = 0; i < 10; i++) { 
     v.push_back(i); 
    } 
    while (!v.empty()) { 
     std::cerr << "We are in the loop, size: " << v.size() << std::endl; 
     int tmp = v.back(); 
     v.pop_back(); 
    } 
}