I have a simple function that loops while there are still elements in a vector. Inside the loop, a single element is popped from the end of the vector using pop_back(). For some reason my code is removing 2 elements every time this is called.
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();
}
The output is as follows:
We are in the loop, size: 3
We are in the loop, size: 1
To clarify, this is the output of the exact code above.
EDIT:
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;
}
Output:
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
EDIT 2:
I changed my implementation from vector to deque. Using the exact same commands I’ve managed to achieve the desired output:
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
Still can’t explain the behaviour from before; thanks for the help everyone.
As Kerrek SB mentioned error is not in the code given, I tried following code and it works fine.