To remove a specific item from a vector in C++, you can use the erase
method along with the std::remove
algorithm.
In this example,
<vector>
and <algorithm>
, and <iostream>
.vec
and initialize it with some integer values.item_to_remove
.std::remove
algorithm to shift all elements that are not equal to item_to_remove
to the front of the vector, and return an iterator to the new logical end of the vector.erase
method to remove the elements from the logical end to the actual end of the vector.#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
int item_to_remove = 30;
vec.erase(std::remove(vec.begin(), vec.end(), item_to_remove), vec.end());
std::cout << "Vector after removing the item " << item_to_remove << ": ";
for (int val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing the item 30: 10 20 40 50
In this example,
<vector>
and <algorithm>
, and <iostream>
.removeItem
that takes a reference to a vector and the item to remove as parameters.std::remove
algorithm to shift all elements that are not equal to the specified item to the front of the vector, and return an iterator to the new logical end of the vector.erase
method to remove the elements from the logical end to the actual end of the vector.vec
and initialize it with some integer values.item_to_remove
.removeItem
function, passing vec
and item_to_remove
as arguments.#include <vector>
#include <algorithm>
#include <iostream>
void removeItem(std::vector<int> &vec, int item_to_remove) {
vec.erase(std::remove(vec.begin(), vec.end(), item_to_remove), vec.end());
}
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
int item_to_remove = 30;
removeItem(vec, item_to_remove);
std::cout << "Vector after removing the item " << item_to_remove << ": ";
for (int val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing the item 30: 10 20 40 50
In this tutorial, we learned How to Remove Specific Item from a Vector in C++ language with well detailed examples.