2011-11-04 81 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(); 
    } 
}