I am trying to understand the behavior of vector::pop_back()
. So I have following code snippet:
vector<int> test;
test.push_back(1);
test.pop_back();
cout << test.front() << endl;
Maybe it is right but it surprises me that it prints out 1. So I am confused. Is pop_back()
only able to remove the element has index > 0
?
Thanks in advance!
You are invoking undefined behaviour by calling front
on an empty vector. That's like indexing out of the bounds of an array. Anything could happen, including returning 1
.
pop_back
here leaves the vector empty. Accessing an empty vector's front()
is undefined behavior. This means that anything can happen - there's no predicting what. It could crash, it could return 1, it could return 42, it could print "Hello, world!", it could erase your hard drive, or it could summon demons through your nasal passages. Any of these are acceptable actions, as far as C++ is concerned - here it just happened to end up returning 1
. Don't rely on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With