矢量pop_back()删除多个条目

时间:2011-11-04 18:31:35

标签: c++

我有一个简单的函数循环,而向量中仍有元素。在循环内部,使用pop_back()从向量的末尾弹出单个元素。出于某种原因,我的代码每次调用时都会删除2个元素。

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:

我将实现从vector更改为deque。使用完全相同的命令,我已设法实现所需的输出:

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

仍然无法解释之前的行为;感谢大家的帮助。

1 个答案:

答案 0 :(得分: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();
    }
}