C++ Vector pop_back()删除多个条目

C++ Vector pop_back()删除多个条目,c++,C++,我有一个简单的函数,在向量中仍然有元素时循环。在循环内部,使用pop_back()从向量的末尾弹出一个元素。出于某种原因,每次调用时,我的代码都会删除2个元素 vector<Vertex> vertices; while ( vertices.size() != 0 ) { std::cerr << "We are in the loop, size: " << vertices.size() << std::endl; Vert

我有一个简单的函数,在向量中仍然有元素时循环。在循环内部,使用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();
}
为了澄清这一点,这是上述确切代码的输出

编辑:

编辑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
仍然无法解释以前的行为;谢谢大家的帮助。

正如前面提到的错误不在给出的代码中一样,我尝试了以下代码,效果很好

#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();
    }
}
#包括
#包括
int main(int argc,字符**argv){
std::向量v;
对于(int i=0;i<10;i++){
v、 推回(i);
}
而(!v.empty()){

std::cerr$100错误“未显示在此处”。此外,始终使用
!empty()
,而不是
size()!=0
。在弹出前打印出大小。您可能无意中弹出/删除了省略代码中的其他位置的元素。大小是否与您在
pop\u back()之前预期的大小相同
call?我们需要一个小的可编译示例来重现问题。创建一个小的可编译示例可能会让您在代码的另一部分中偶然发现错误。@Loki,我接受您的建议;谢谢。
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
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
#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();
    }
}