Vector pop_back()删除多于1个条目

Vector pop_back() removing more than 1 entry

本文关键字:1个 删除 pop back Vector      更新时间:2023-10-16

我有一个简单的函数,当向量中仍然有元素时循环。在循环内部,使用pop_back()从vector的末尾弹出一个元素。由于某种原因,我的代码每次调用它时都会删除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

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

由于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();
    }
}