Vector pop_back()删除多于1个条目
Vector pop_back() removing more than 1 entry
我有一个简单的函数,当向量中仍然有元素时循环。在循环内部,使用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();
}
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运算符C++ "delete []"仅删除 2 个前值
- 删除列表中的第n个元素
- 为什么我的双向链表删除函数会删除多个节点?
- 关于比较两个无序数组并删除 a[] 中可以在 b[] 中找到的元素的问题
- 如何删除字符串中的前 2 个字符(如果它有"-")
- 删除列表 c++ 中的最后 3 个元素
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 删除功能不适用于串行通信后多个循环中的多个实例
- 如何插入 4 个空格宽的制表符并将它们删除两个空格?
- 从队列中删除第一个元素C++
- 将内容从第一个文件("constituencies")移动到第二个文件("temp")并在之后重命名时,我的文件被删除
- 删除第 I 个元素
- 从 AVL 树中删除指向 1 个或多个值的键
- 复制后删除原始数组指针将前 3 个字节设置为 0
- 如何从提升::multi_index中删除多个元素?
- 双向链表 - 无法删除第一个节点
- C++ 链表:它不会删除第一个输入
- 如何避免多个删除程序 lambda
- 带有第二个删除器的Shared_ptr链/分支