Why is this statement:
cout << values[0] << " " << values[1] << " " << values[2] << endl;
Showing
1 2 3
Even though pop back was used to remove the last element from the vector. Shouldn't the values be removed too? Or does the vector resize even though the element is removed?
Here is the sample code:
// This program demonstrates the vector pop_back member function.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> values;
// Store values in the vector.
values.push_back(1); // Last element in values is 1
values.push_back(2); // Now elements in values are 1,2
values.push_back(3); // Now elements in values are 1,2,3
cout << "The size of values is " << values.size() << endl; // values has 3 elements
// Remove a value from the vector.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl; // 1 is Removed thus size is 2
cout << values[0] << " " << values[1] << " " << values[2] << endl;
// Now remove another value from the vector.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
cout << values[0] << " " << values[1] << " " << values[2] << endl;
// Remove the last value from the vector.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
cout << values[0] << " " << values[1] << " " << values[2] << endl;
return 0;
}
"values" and "elements" are the same thing. pop_back() removes the last value from the vector, if the vector is not empty.
vector is designed so that it is the programmer's responsibility to not access out of bounds of the vector. If a vector has 2 elements and you try to access the third element via any method except for at(), you cause undefined behaviour.
To get bounds checking, use values.at(0) instead of values[0], etc., and include a try...catch block to catch the resulting exception.
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