c++ remove last element from vector
To remove the last element from a vector in C++, you can use the pop_back()
function. This function removes the last element from the vector and reduces the size of the vector by one.
Here are the steps to remove the last element from a vector:
- Declare a vector variable and initialize it with some elements:
std::vector<int> myVector = {1, 2, 3, 4, 5};
- Use the
pop_back()
function to remove the last element from the vector:
myVector.pop_back();
After executing the pop_back()
function, the last element (5) will be removed from the vector.
Example:
Here's a complete example that demonstrates the removal of the last element from a vector:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5};
// Display the vector before removing the last element
std::cout << "Before removing the last element: ";
for (const auto& element : myVector) {
std::cout << element << " ";
}
std::cout << std::endl;
// Remove the last element from the vector
myVector.pop_back();
// Display the vector after removing the last element
std::cout << "After removing the last element: ";
for (const auto& element : myVector) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Before removing the last element: 1 2 3 4 5
After removing the last element: 1 2 3 4
In this example, the vector myVector
initially contains the elements 1, 2, 3, 4, and 5. The pop_back()
function is then used to remove the last element (5) from the vector. Finally, the contents of the vector are displayed before and after the removal of the last element.