How to remove a specific element from a vector
In C++, you can use the erase() function to remove a specified element from a vector. The erase() function takes an iterator as a parameter, which points to the element to be deleted. Here is an example code for deleting a specified element in a vector:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec {1, 2, 3, 4, 5};
// 删除元素3
for (auto it = vec.begin(); it != vec.end(); ++it) {
if (*it == 3) {
vec.erase(it);
break;
}
}
// 打印删除元素后的vector
for (const auto& num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
In the above code, we use an iterator to traverse the vector. When we find the element to delete, we call the erase() function to remove it. It is important to note that the iterator becomes invalid after calling erase() so we use a break statement to exit the loop after deleting the element. Finally, we print the vector after deleting the element, resulting in: 1 2 4 5.