C++ Vector Erase: Delete Elements by Position
To remove elements at a specific position in a vector, you can use the erase() method. This method takes an iterator as a parameter to indicate the position of the element to be deleted.
Here is a sample code:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 删除第三个元素(索引为2)
vec.erase(vec.begin() + 2);
// 打印删除元素后的vector
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
In the example above, we used the erase() method to delete the third element (index 2).
Please note that the size of the vector will decrease after deleting an element, so make sure the deletion position is valid.