I am not sure what's wrong with this code :
std::vector<int> myVector(0);
if (myVector.back() == 12)
myVector.push_back(12);
It seems that calling back() on an empty vector crashes the program.
I don't understand why it's crashing? Do we need to check the length of the vector before calling back()
? or is possible that it's a bug?
The documentation says, that if the vector is empty it return an undefined value.
do we need to check the length of the vector before calling back() ?
In a word: yes. This is your bug, your vector is empty so there is no "back" element.
The documentation should say (if it says anything at all) that calling back()
on an empty vector causes undefined behavior, not that it returns an undefined value.
c++11 standard tells this:
23.3.2.8 / 3
The effect of calling front() or back() for a zero-sized array is undefined.
Since the behaviour is undefined, anything can happen. You were lucky to get a crash.
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