-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
仍然無法解釋之前的行爲;感謝大家的幫助。
$ 100錯誤是「此處未顯示」。另外,總是使用'!empty()'而不是'size()!= 0'。 –
在彈出之前打印出大小。您可能會意外彈出/刪除省略代碼中其他位置的元素。 – Kevin
在pop_back()調用之前,您期望的大小是多少? – aschepler