remove element from vector c++ by index
Code Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int indexToRemove = 2;
vec.erase(vec.begin() + indexToRemove);
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
Explanation:
- Step 1: Include the necessary libraries for input/output operations and vectors.
- Step 2: Define the main function.
- Step 3: Create a vector of integers and initialize it with some values.
- Step 4: Define the index of the element to remove from the vector.
- Step 5: Use the
erase
function to remove the element at the specified index from the vector. - Step 6: Iterate through the modified vector and print its elements.
- Step 7: Return 0 to indicate successful execution.